< Previous | Contents | Next >

Altering Global Variables

Just as you can access a global variable from anywhere in your program, you can alter one from anywhere in your program, too. Thats what I do next, when I call the change_global() function. The key line of the function assigns 10 to the global variable glob.

glob = -10; // change global variable glob

To show that it worked, I display the variable in change_global() with:

cout << "In change_global() glob is: " << glob << "\n\n";

Then, back in main(), I send glob to cout with:

cout << "In main() glob is: " << glob << "\n\n";

Because the global variable glob was changed, 10 is displayed.

170 Chapter 5 n Functions: Mad Lib