< Previous | Contents | Next >

Hiding Global Variables

You can hide a global variable like any other variable in a scope; you simply declare a new variable with the same name. Thats exactly what I do next, when I call hide_global(). The key line in that function doesnt change the global variable glob; instead, it creates a new variable named glob, local to hide_global(), that hides the global variable.

int glob = 0; // hide global variable glob

As a result, when I send glob to cout next in hide_global() with the following line, 0 is displayed.

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

The global variable glob remains hidden in the scope of hide_global() until the function ends.

To prove that the global variable was only hidden and not changed, next I display glob back in main() with:

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

Once again, 10 is displayed.


Tra p

image

Although you can declare variables in a function with the same name as a global variable, it’s not a good idea because it can lead to confusion.

image