< Previous | Contents | Next >
The Scoping program demonstrates scopes. The program creates three variables with the same name in three separate scopes. The program displays the values of
162 Chapter 5 n Functions: Mad Lib
these variables, and you can see that even though they all have the same name, the variables are completely separate entities. Figure 5.3 shows the results of the program.
Figure 5.3
Even though they have the same name, all three variables have a unique existence in their own scopes.
You can download the code for this program from the Course Technology website (www.courseptr.com/downloads). The program is in the Chapter 5 folder; the filename is scoping.cpp.
// Scoping
// Demonstrates scopes #include <iostream> using namespace std; void func();
int main()
{
int var = 5; // local variable in main() cout << "In main() var is: " << var << "\n\n";
func();
cout << "Back in main() var is: " << var << "\n\n";
{
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";
cout << "At end of main() var created in new scope no longer exists.\n"; cout << "At end of main() var is: " << var << "\n";
return 0;
}
void func()
{
int var = -5; // local variable in func() cout << "In func() var is: " << var << "\n\n";
}