| I l @ ve RuBoard |
Chapter 9. Variable Scope and Functions
So far you have been using only global variables. These are
|
| I l @ ve RuBoard |
| I l @ ve RuBoard |
9.1 Scope and Storage Class
All
Figure 9-1. Local and global variables
It is possible to declare a local variable with the same
Figure 9-2. Hidden variables
The variable count is declared both as a local variable and as a global variable. Normally the scope of count (global) would be the entire program, but when a variable is declared inside a block, that instance of the variable becomes the active one for the length of the block. The global count has been hidden by the local count for the scope of this block. The shaded area in the figure shows where the scope of count (global) is hidden. It is not good programming practice to hide variables. The problem is that when you have the statement: count = 1;
it is difficult to tell which
count
you are referring to. Is it the global
count
”the one declared at the top of
main
”or the one in the middle of the
while
loop? It is better to give these variables different
The
storage class
of a variable may be either
permanent
or
temporary
. Global variables are always permanent. They are created and
The size of the stack depends on the system and compiler you are using. On many Unix systems, the program is automatically allocated the largest possible stack. On other systems, a default stack
Local variables are temporary unless they are declared static .
Example 9-1 illustrates the difference between permanent and temporary variables. We have
In the loop both variables are incremented. However, at the top of the loop -- temporary is initialized to 1. Example 9-1. perm/perm.cpp
#include <iostream>
int main( ) {
int counter; // loop counter
for (counter = 0; counter < 3; ++counter) {
int temporary = 1;
static int permanent = 1;
std::cout << "Temporary " << temporary <<
" Permanent " << permanent << '\n';
++temporary;
++permanent;
}
return (0);
}
The output of this program looks like: Temporary 1 Permanent 1 Temporary 1 Permanent 2 Temporary 1 Permanent 3
Table 9-1 describes the different ways a variable can be declared. Table 9-1. Declaration modifiers
9.1.1 The for ScopeThe for statement is similar to a set of curly braces in that you can declare variables inside the statement whose scope goes from the start of the for to the end of the statement. (This includes the statement or block controlled by the for .) In the following statement:
for (int count = 0; count < MAX; ++count)
sum += count;
// count is out of scope from here on.
the variable count is declared inside the for . Its scope is to the end of the statement; the scope ends with the first semicolon after the for . |
| I l @ ve RuBoard |