4F. Compound Statements and Scope

A particular variable x only exists in a limited part of a program that is called the scope of x. A compound statement limits scope: A variable x only exists inside the smallest compound statement that holds the declaration of x. For example:

  {
    int v1 = 0;
    {
      int v2 = 1;

      // v1 and v2 can be used here.
    }

    // Only v1 can be used here.
  }

  // Neither v1 nor v2 can be used here.


Shadowing and a standard

Shadowing refers to declaring a new variable within the scope of another variable that has the same name. For example, in

  {
    int x = 0;
    {
      int x = 1;
      x = x + 3;
    }
  }
we say that the second variable x shadows the first one. Inside the smaller compound statement, x refers to the variable called x that was created inside the smaller compound statement; the program can't see the first x because it is in the shadow of the second x.

C++ allows shadowing as long as the shadowing variable is declared inside a smaller compound statement than the one where the shadowed variable is declared.

If that is confusing, it does not matter. The standards for this course require that you not make use of shadowing.