C++ · Module 2 · Lesson 21 min read

Variables & Initialization

Declaring a variable

ini
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

StyleExampleNotes
Copy initializationint a = 5;familiar, C-style
Direct initializationint b(5);used with constructors
Brace (uniform) initialization ✅int c{5};C++11, blocks narrowing
Value initializationint d{};zero (0, 0.0, false)

Why braces? Narrowing protection

ini
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

ini
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 =
ini
int score{10};   // initialization
score = 20;      // assignment

Variable naming tips

  • Descriptive: monthly_budget, not mb
  • 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

C++
#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
*/