Choose types and initialize objects
C++ types describe representable values and supported operations. Use int for suitable whole-number ranges, double for approximate real-number calculations, bool for true/false and std::string for text. The exact sizes of built-in numeric types depend on the implementation.
Initialization that catches narrowing
#include
#include
#include
int main() {
int lessons{12};
double average{78.5};
bool passed{average >= 40.0};
std::string course{"C++"};
auto next = lessons + 1;
std::cout << course << ' ' << next << ' ' << passed << '\n';
std::cout << std::numeric_limits::max() << '\n';
} The first line is C++ 13 1; the maximum int value printed on the second line depends on the implementation. Brace initialization rejects narrowing such as int count{3.5}; rather than silently discarding the fraction.
What auto does and does not do
auto deduces a type from an initializer at compile time. It does not create a dynamically typed variable. auto ratio = 5 / 2; deduces int with value 2; auto ratio = 5.0 / 2; deduces double with value 2.5. A plain auto declaration usually drops reference and top-level const qualifiers; use auto& when you intend to refer to an existing object.
Modifiers and range
short, long, long long and unsigned express variations of integer types. Do not assume long is always 64 bits. Use numeric_limits or appropriate fixed-width types from cstdint when an interface needs a specific width and that type is provided. Unsigned subtraction can wrap; signed overflow is undefined behavior. A larger type is not a substitute for checking an untrusted input range.
const and constexpr
const prevents modification through the named object after initialization. constexpr requires a constant-expression initializer for a variable and is useful for compile-time values such as a fixed array extent. Neither should be used as a decorative keyword: choose it to express a real rule.
Practice and answers
- Predict
auto x = 7 / 2;. It is int with value 3. - Initialize every local variable before reading it.
int value{};produces zero. - Store a person's age and a measured temperature. Explain why their valid ranges differ.
- Does assigning 2.5 to an existing auto-deduced int turn it into double? No; the type is fixed and the assignment converts the value.
हिन्दी संकेत: auto type inference है, runtime type change नहीं। Brace initialization और range checks से accidental data loss कम करें।