20.2.  Identifier Scope

[ fromfile: scopestorage.xml id: scopes ]

Every identifier has a scope which is determined by where it was declared. The scope of an identifier in a program is the region(s) of the program within which it can be used. Using a name outside of its scope is an error.

The same name may declared/used in different scopes. Ambiguities are resolved as follows:

  1. The name from the most local scope is used.

  2. If the name is not defined in the most local scope, the same name defined in the nearest enclosing scope will be used.

  3. If the name is not defined in any enclosing scope, then the compiler will report an error.

There are five possible scopes in C++.

  1. Block scope (local to a block of statements)

  2. Function scope (the entire extent of a function) [55]

  3. Class scope (the entire extent of a class, including its member functions)

  4. File scope (the entire extent of a source code file)

  5. Global scope (the entire extent of a program)

Because the compiler only deals with one source file at a time, only the linker can tell the difference between global and file scope, as Example 20.3 shows.

Example 20.3.  Global vs File scope

In file 1:

int g1;        // global
int g2;        // global
static int g3; // keyword static limits g3 to file scope
(etc.)

In file 2:

int g1;           // linker error!
extern int g2;    // OK, share variable space
static int g3;    // okay, 2 different variable spaces
(etc.)



[55] Only labels have function scope.