4C. Variable Initialization


Initialization and uninitialized variables

A program initializes a variable x when it first stores a value into x. For example, in

  int y;
  y = 1;
the second line initializes y to 1. (Do not confuse initializing a variable with declaring it.)

With some exceptions that we will see later, C++ does not initialize variables automatically. If you use the value of a variable x before storing any value into x, there will be a value in x, but you have no way of knowing what that value is. (The value of a variable is somewhere stored in the memory. The memory that holds x might have previously held something else. Whatever happens to be in that memory when x is declared, that is the unknown initial value of x.)

The standards for this course require a program never to use the value of a variable before the variable has been initialized.


Combining declaration and initialization

You can initialize a variable in its declaration. For example, declaration

  int z = 0;
is equivalent to
  int z;
  z = 0;
and
  double r = 0.0, s = 0.5;
is equivalent to
  double r, s;
  r = 0.0;
  s = 0.5;


Exercises

  1. What is the difference between declaring and initializing a variable? Answer

  2. If variable x is declared by

      double x;
    
    what value does x initially contain? Answer

  3. What happens if your program uses a variable before storing anything in it? Answer