Scope and Visibility
Scope
The scope of an identifier is a part of the program in which the identifier can be used to access its object. There are different categories of scope: block (or local), function, function prototype, and file. These categories depend on how and where identifiers are declared.
- Block: The scope of an identifier with block (or local) scope starts at the declaration point and ends at the end of the block containing the declaration (such block is known as the enclosing block). Parameter declarations with a function definition also have block scope, limited to the scope of the function body.
- File: File scope identifiers, also known as globals, are declared outside of all blocks; their scope is from the point of declaration to the end of the source file.
- Function: The only identifiers having function scope are statement labels. Label names can be used with goto statements anywhere in the function in which the label is declared. Labels are declared implicitly by writing
label_name:
followed by a statement. Label names must be unique within a function. - Function prototype: Identifiers declared within the list of parameter declarations in a function prototype (not as a part of a function definition) have a function prototype scope. This scope ends at the end of the function prototype.
Visibility
The visibility of an identifier is a region of the program source code from which an identifier’s associated object can be legally accessed.
Scope and visibility usually coincide, though there are circumstances under which an object becomes temporarily hidden by the appearance of a duplicate identifier: the object still exists but the original identifier cannot be used to access it until the scope of the duplicate identifier ends.
Technically, visibility cannot exceed a scope, but a scope can exceed visibility. See the following example:
void f (int i) { int j; // auto by default j = 3; // int i and j are in scope and visible { // nested block double j; // j is local name in the nested block j = 0.1; // i and double j are visible; // int j = 3 in scope but hidden } // double j out of scope j += 1; // int j visible and = 4 } // i and j are both out of scope
What do you think about this topic ? Send us feedback!