< Previous | Contents | Next >
The Global Reach program demonstrates global variables. The program shows how you can access a global variable from anywhere in your program. It also shows how you can hide a global variable in a scope. Finally, it shows that you can change a global variable from anywhere in your program. Figure 5.4 shows the results of the program.
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 global_reach.cpp.
// Global Reach
// Demonstrates global variables #include <iostream>
Using Global Variables 167
Figure 5.4
You can access and change global variables from anywhere in a program—but they can also be hidden in a scope as well.
using namespace std;
int glob = 10; // global variable void access_global();
void hide_global(); void change_global();
int main()
{
cout << "In main() glob is: " << glob << "\n\n"; access_global();
hide_global();
cout << "In main() glob is: " << glob << "\n\n";
change_global();
cout << "In main() glob is: " << glob << "\n\n";
return 0;
}
168 Chapter 5 n Functions: Mad Lib
void access_global()
{
cout << "In access_global() glob is: " << glob << "\n\n";
}
void hide_global()
{
int glob = 0; // hide global variable glob
cout << "In hide_global() glob is: " << glob << "\n\n";
}
{
glob = -10; // change global variable glob
cout << "In change_global() glob is: " << glob << "\n\n";
}