5.8. Scope


Scope of a variable

The scope of a variable is that part of a program where that variable can be used by writing its name.


Scope among function definitions

Imagine a household with an individual named Bob. Now imagine a second household that also has someone named Bob. Obviously, the two Bobs are not the same person, and if you call out for Bob in one of the households, it is obvious which one you are calling.

Think of each function definition as a separate household. Its variables are not the same as the variables in any other function definition, even if two variables share the same name. No function can make direct use of variables that are created in another function definition.

In fact, scope is even more restrictive than that. When a function is called, a frame is created for it in the run-time stack. Variables are local to a single frame, or to a single function call. No function call can make direct use of variables that belong to another function call, even if the two calls are to the same function.


Scope within a function definition

Even within a single function definition, variables can have limited scope. Generally, a variable that is created inside a compound statement can only be used inside that compound statement (and can also only be used after its definition). For example,

  void example(int x)
  {
    {
      int r = 1;
      ...
    }
    int w = r;
  }
is not allowed because variable r only exists inside the compound statement where it is created.


Shadowing

C++ allows you to create a variable inside a compound statement that has the same name as another variable that is defined outside of that compound statement. That is called shadowing. For example,

  int shadow(int x)
  {
    int w = x;
    {
      int x;
      …
    }
  }
uses shadowing. Any use of variable x inside the compound statement where x is created (and after the point where x is created) refers to that variable x. Because the inner definition of x shadows the parameter called x, it is not possible to refer to parameter x where variable x is in scope.

Shadowing is often confusing. For example,

  void shadow2(int& n)
  {
    for(int i = 0; i < 10; i++)
    {
      int n = n + 1;
    }
  }
is allowed, but it does not change the reference parameter n at all. The body of the for-loop creates a new variable called n, and stores a value that is one larger than the parameter n into it. Do not write a type in front of a variable unless you intend to create a new variable.

The coding standards for this course require you not to make use of shadowing.