< previous page page_391 next page >

Page 391
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
C++ defines three categories of scope for any identifier.*
1. Class scope
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
This term refers to the data type called a class, which we introduced briefly in Chapter 4. We postpone a detailed discussion of class scope until Chapter 15.
2. Local scope
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
The scope of an identifier declared inside a block extends from the point of declaration to the end of that block.
3. Global (or file) scope
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
The scope of an identifier declared outside all functions and classes extends from the point of declaration to the end of the entire file containing the program code.
C++ function names have global scope. (There is an exception to this rule, which we discuss in Chapter 15 when we examine C++ classes.) Once a function name has been declared, the function can be invoked by any other function in the rest of the program. In C++ there is no such thing as a local functionthat is, you cannot nest a function definition inside another function definition.
Global variables and constants are those declared outside all functions. In the following code fragment, gamma is a global variable and can be accessed directly by statements in main and SomeFunc.
int gamma;    // Global variable

int main()
{
    .
    .
    .
}

void SomeFunc()
{
    .
    .
    .
}
When a function declares a local identifier with the same name as a global identifier, the local identifier takes precedence within the function. This principle is called name precedence or name hiding.
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif 3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
*Technically, C++ defines four scope categories. The fourth relates to a statement called a goto statement, which we do not discuss in this book.

 
< previous page page_391 next page >