Scope

An identifier (variable or function name) can only be used within a region of program text called its scope. Use of an identifier outside of its scope (e.g. if it has not been defined or declared) will generate a compiler error about an unknown name. There are four kinds of scope:

Function Scope

A label name is the only kind of identifier that has function scope and that does not need to be explicitly declared. It can be used (via a goto statement) anywhere in the function in which it appears. It is declared implicitly by its syntactic appearance (followed by a : and then a statement). For example:

	loop: statement_1;
	statement_2;
	goto loop;

Duplicate label names within the same function will cause a compilation error. A label that is not referred to will generate a compiler warning. A label can appear before or after a goto which referes to it.

Global and File Scope

The scope of all other identifiers is determined by the placement of their declarations, unless explicitly qualified by a scope keyword. If the placement is outside of a function, then that identifier has file scope - extending from that point to the end of the file (and all subsequently included files - see preprocessor). Unless the identifier (variable or function)a is also declared to be static then that identifier also has global scope. There is a global keyword but it is not really needed. To refer to an identifier with global scope in another file of the same program that identifier needs to be declared in that other file (or by a file included within that file). In the cases of a function the declaration is needed. In the case of a variable the declaration is needed with the keyword extern before it, see example below:

	extern int foop;

Block Scope

If the declaration appears within a block or a function body then, the identifier has block scope, which extends until the closing } of the block. If an outer declaration (file or block) of the same identifier exists, then it is hidden until the closing brace, }, of the block, after which the scope of the hidden identifier resumes.

Example

Here is an example of some variable with block scope, using a vertical line on the left to indicate when the scope is active. Only the scopes for the different y's are shown:

               {
        |      int x,y;
        |      ...
        |      for(x=0;x<9;x++) {
          |       double y;
          |       ...
          |       ...
          |       ...
          |       while(x!=4) {
            |        char y;
            |        ...
            |        ...
            |        if(!y) x=4;
            |        ...
            |        ...
            |        ...
            |     }
          |       ...
          |       ...
          |    }
        |      ...
        |      ...

© 1991-2008 Prem Sobel. All Rights Reserved.