Variables & Initialization
Declaring a variable
type name; // declaration (value is GARBAGE for local int/double!)
type name = value; // declaration + initialization
⚠️ A local variable without an initializer has an indeterminate value. Reading it is a bug. Always initialize.
Ways to initialize
| Style | Example | Notes |
|---|---|---|
| Copy initialization | int a = 5; | familiar, C-style |
| Direct initialization | int b(5); | used with constructors |
| Brace (uniform) initialization ✅ | int c{5}; | C++11, blocks narrowing |
| Value initialization | int d{}; | zero (0, 0.0, false) |
Why braces? Narrowing protection
int x = 3.9; // compiles, silently becomes 3 😬
int y{3.9}; // ERROR: narrowing conversion ✅ the compiler protects you
Narrowing = converting to a type that can't hold the value (double → int, big int → char).
Multiple variables
int a = 1, b = 2, c = 3; // OK, but one per line is clearer
Assignment vs initialization
- Initialization: giving a value when the variable is created
- Assignment: changing it later with
=
int score{10}; // initialization
score = 20; // assignment
Variable naming tips
- Descriptive:
monthly_budget, notmb - Loop counters may be short:
i,j - Declare variables close to where they're used
Global variables
Variables declared outside functions are global, and are zero-initialized automatically. Avoid them where possible — any function can change them.
Example
#include <iostream>
int global_counter; // globals are zero-initialized
int main() {
int a = 5; // copy initialization
int b(10); // direct initialization
int c{15}; // brace initialization
int d{}; // value initialization -> 0
double rate{}; // -> 0.0
bool done{}; // -> false
std::cout << "a=" << a << " b=" << b << " c=" << c << " d=" << d << '\n';
std::cout << "rate=" << rate << " done=" << std::boolalpha << done << '\n';
std::cout << "global_counter=" << global_counter << '\n';
int truncated = static_cast<int>(3.9); // explicit conversion: we accept losing .9
std::cout << "truncated=" << truncated << '\n';
// int bad{3.9}; // error: narrowing conversion from double to int
c = c + a; // assignment, not initialization
std::cout << "c after assignment=" << c << '\n';
return 0;
}
/* Output:
a=5 b=10 c=15 d=0
rate=0 done=false
global_counter=0
truncated=3
c after assignment=20
*/