Warrior, the real problem with globals has nothing to do with performance. It is
all about maintainability and understandability.
The definition of a
correct programmer is one which generates the correct output for all possible inputs. (Not all inputs are valid). The only way to prove that a program is correct is to know the state of the program at all points for a given input or inputs. Because global variables can be modified
absolutely anywhere in the program, any code that uses the global variables is a real strain to understand exactly what it does and what output it generates.
Consider the following examples.
1 2 3 4 5 6 7 8 9 10 11 12 13
|
// Example A
int global_A;
int multiply( int b )
{
return global_A * b;
}
// Example B
int multiply( int a, int b )
{
return a * b;
}
|
In example A, for any given input b, I cannot say what the output of the function will be unless I know the value of global_A. But global_A can be set
anywhere in the million-line program that it is part of. The only way I know what multiply( 5 ) returns is if I can know what global_A was last set to. In a large program, this is generally very hard if not impossible.
In example B, I know what multiply( 4, 5 ) does. I know what multiply( some_var_x, some_var_y ) does only if I know the values of some_var_x and some_var_y.
C++ experts generally recommend that you minimize the scope of your variables only to what you need. Why? Well, two reasons. One is memory usage, though if we're talking simple ints and chars and such it will take a lot of them to make a difference. The other is to aid in the understanding of the program and proving correctness.
[Ok, there is a third reason, particularly when dealing with objects that need to be constructed with parameters, but I won't go into that.]