< Previous | Contents | Next >

Working with Nested Scopes

You can create a nested scope with a pair of curly braces in an existing scope. Thats what I do next in main(), with:


{

cout << "In main() in a new scope var is: " << var << "\n\n";


cout << "Creating new var in new scope.\n";

int var = 10; // variable in new scope, hides other variable named var cout << "In main() in a new scope var is: " << var << "\n\n";

}


This new scope is a nested scope in main(). The first thing I do in this nested scope is display var. If a variable hasnt been declared in a scope, the computer looks up the levels of nested scopes one at a time to find the variable you requested. In this case, because var hasnt been declared in this nested scope, the computer looks one level up to the scope that defines main() and finds var. As a result, the program displays that variables value5.

However, the next thing I do in this nested scope is declare a new variable named var and initialize it to 10. Now when I send var to cout, 10 is displayed. This time the computer doesnt have to look up any levels of nested scopes to find var; theres a var local to this scope. And dont worry, the var I first declared in main() still exists; its simply hidden in this nested scope by the new var.


Tra p

image

Although you can declare variables with the same name in a series of nested scopes, it’s not a good idea because it can lead to confusion.

image


Next, when the nested scope ends, the var that was equal to 10 goes out of scope and ceases to exist. However, the first var I created is still around, so when I display var for the last time in main() with the following line, the program displays 5.

cout << "At end of main() var is: " << var << "\n";

166 Chapter 5 n Functions: Mad Lib


Hi n t

image

When you define variables inside for loops, while loops, if statements, and switch statements, these variables don’t exist outside their structures. They act like variables declared in a nested scope. For example, in the following code, the variable i doesn’t exist outside the loop.

for(int i = 0; i < 10; ++i)

{

cout << i;

}

// i doesn’t exist outside the loop

But beware—some older compilers don’t properly implement this functionality of standard C++. I recommend that you use an IDE with a modern compiler, such as Microsoft Visual C++ 2010 Express Edition. For step-by-step instructions on how to create your first project with this IDE, check out Appendix A.

image