next up previous
Next: Argument Passing Up: TwelfthWeek Previous: Objectives

Scope

Every variable has a scope - a section of code within which it can be accessed. To access a variable, the variable must be in scope - visible - at the point of use. For instance, a variable defined within the initializer of a for loop can't be used outside the loop, because its scope is limited to the loop:
for(int i = 0; i< 10; ++i)
    cout << i;
cout << "The final value of i is " << i;	//error

i is accessible only within the loop, so the second cout is not allowed. We say that the scope of i is the loop or, in other words, i is not in scope in the second cout. So the compiler, when it sees the second cout, says, in effect, ``i? what's that?"

Not only does scoping prevent access to variables but it also allows you to have two different variables in different scopes. For instance:

void foo() {
    int i = 7;
    ...
    }

void bar() {
    string i = "No problem";
    ...
    }

Here we have two variables named i, but there's no problem since they are in different scopes. If a statement within foo() accesses i, it will get foo()'s copy of i, and similarly for a statement within bar(). Changing one will not affect the other (after all, they are different variables). The two variables can be of different types and have no connection at all.

Scopes can also be nested - you can have one scope defined within another. Here's an example:

void foo(int something) {
    int i = 4;
    if(something > 8) {
        string i = "what happens";
        cout << i;	//what does this print?
        }
    cout << i;	//prints 4
    }
Here we have two variables in two different scopes - one within the scope of the function foo(), and the other restricted to the body of the if. What makes this example different (and interesting) from the previous one is that one scope is nested - contained - within the other. It should be clear that the second cout prints 4 - that's the only i which is in scope at that point. But both i's are in scope for the first cout. So what happens? C++ resolves this by using the variable defined in the innermost scope. If the compiler ever has to choose between two variables of the same name, it prefers the one defined in the inner scope. We say that the inner i (the string) hides the outer one.

Scope applies to all identifiers - names (of variables, functions, classes, etc), not just local variables.

There is also a global scope - it contains everything that's not defined in any other scope, including global variables and the functions themselves defined above.


next up previous
Next: Argument Passing Up: TwelfthWeek Previous: Objectives
cs101 senior TA 2005-10-24