20.2.  Identifier Scope

[ fromfile: scopestorage.xml id: scopes ]

Every identifier has a scope 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 recognized and used. Attempting to use a name outside of its scope is an error.

The same name may be 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, the compiler reports an error.

We discuss six different scopes in C++.

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

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

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

  4. Namespace scope (an extensible block scope with features of class scope)

  5. File scope (from the declaration to the bottom of one source code file)

  6. Global scope (similar to file scope but can be extended to multiple source code files)



[109] Only labels have function scope.