|
|
|
|
|
|
|
When you write C++ programs, you rarely declare global variables. There are negative aspects to using global variables, which we discuss later. But when a situation crops up where you have a compelling need for global variables, it pays to know how C++ handles these declarations. The rules for accessing identifiers that aren't declared locally are called scope rules. |
|
|
|
 |
|
 |
|
|
Scope Rules The rules that determine where in the program an identifier may be accessed, given the point where that identifier is declared. |
|
|
|
|
|
|
|
|
In addition to local and global access, the C++ scope rules define what happens when blocks are nested within other blocks. Anything declared in a block that contains a nested block is nonlocal to the inner block. (Global identifiers are nonlocal with respect to all blocks in the program.) If a block accesses any identifier declared outside its own block, it is a nonlocal access. |
|
|
|
 |
|
 |
|
|
Nonlocal Identifier Any identifier declared outside a given block is said to be nonlocal with respect to that block. |
|
|
|
|
|
|
|
|
Here are the detailed scope rules, excluding class scope and certain language features we have not yet discussed: |
|
|
|
|
|
|
|
|
1. A function name has global scope. Function definitions cannot be nested within function definitions. |
|
|
|
|
|
|
|
|
2. The scope of a formal parameter is identical to the scope of a local variable declared in the outermost block of the function body. |
|
|
|
|
|
|
|
|
3. The scope of a global variable or constant extends from its declaration to the end of the file, except as noted in rule 5. |
|
|
|
|
|
|
|
|
4. The scope of a local variable or constant extends from its declaration to the end of the block in which it is declared. This scope includes any nested blocks, except as noted in rule 5. |
|
|
|
|
|
|
|
|
5. The scope of an identifier does not include any nested block that contains a locally declared identifier with the same name (local identifiers have name precedence). |
|
|
|
|
|
|
|
|
Here is a sample program that demonstrates C++ scope rules. To simplify the example, only the declarations and headings are spelled out. Note how |
|
|
|
|
|