Variable Declarations

Value Initialization

  • When variables are declared, they have an undetermined  value until they are assigned a value for the first time.

  • There are 3 ways of initializing a variable; all 3 are equivalent in C++.

int x;       // value undetermined
int x = 0;   // value 0, via 'c-like initialization'
int x (0);   // value 0, via 'constructor initialization'
int x {0};   // value 0, via 'uniform initialization' (C++11)
  • Automatic initialized to zero :

    • Variables with static storage (such as global variables) that are not explicitly initialized are automatically initialized to zeroes.

    • Variables with automatic storage (such as local variables) that are not explicitly initialized are left uninitialized, and thus have an undetermined value.

Type deduction / Type inference

  • When a new variable is initialized, the compiler can figure out what the type of the variable is automatically by the initializer.

  • The options below decrease readability, since, when reading the code, one has to search for the type of foo  to actually know the type of bar .

With auto  (C++11)
  • The type of the variable will be the same as the type of the value used to initialize it.

int foo = 0;
auto bar = foo;  // the same as: int bar = foo; 
  • History:

    • C does not have general type inference like C++11 auto .

    • In C89 and forward  and in C++98 until before C++11 :

      • auto  does not perform type inference.

      • It is a storage class specifier, not type deduction

With decltype  (C++11)
  • Variables that are not initialized can also make use of type deduction with the decltype  specifier:

int foo = 0;
decltype(foo) bar;  // the same as: int bar;
  • Here, bar  is declared as having the same type as foo .

Declaring many variables

int a, b, c;
  • Is the same as:

int a;
int b;
int c;

Assignment Operations

  • They are expressions that can be evaluated. That means that the assignment itself has a value, and -for fundamental types- this value is the one assigned in the operation.

  • Examples 1 :

    y = 2 + (x = 5);
    
    • y  is assigned the result of adding 2  and the value of another assignment expression (which has itself a value of 5).

    • It is roughly equivalent to:

    x = 5;
    y = 2 + x;
    
  • Examples 2 :

    x = y = z = 5;   
    
    • It assigns 5 to the all three variables: x, y and z; always from right-to-left.