Modern C++ • C++20 baseline
Types, Initialization, and auto
Choose types from meaning, initialize objects immediately, and use auto when the initializer is clear.
Types determine which values an object can represent and which operations make sense. Prefer direct initialization or braces for local objects so accidental uninitialized state is avoided. auto asks the compiler to infer a type from its initializer; it preserves static type checking and is clearest when the expression already communicates the intended type.
Key points
- Use fixed-width integer types only when an exact width is part of the interface.
- Brace initialization rejects many narrowing conversions.
Example
#include <cstdint>
#include <iostream>
int main() {
const std::uint32_t attempts{3};
const auto remaining = attempts - 1;
std::cout << remaining << '\n';
}
What to expect
Practice exercise
Try initializing a std::uint8_t from 300 with braces. Read the compiler diagnostic and explain why narrowing should be handled deliberately.
Key idea: Initialization is part of correctness; use a type whose range matches the domain.