5.9. Scope


Scope among method 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 method definition as a separate household. Its variables are not the same as the variables in any other method definition, even if two variables share the same name. No method can use variables that are created in another method definition.

In fact, scope is even more restrictive than that. When a method is called, a frame is created for it. Variables are local to a single frame, or to a single method call. No method call can use variables that belong to another method call, even if the two calls are to the same method.


Scope within a method definition

Even within a single method 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 only be used after its definition). For example,

  static 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.