Matt said:
What are people's thoughts on global variables in C++?
Global *variables* are bad.
Global *constants* are good.
Why are we taught not to use them in programming?
Is it true that, if you are running two copies of the C program,
one copy can overwrite another copy's global variable?
No.
I know that
you could overwrite a value in a global variable from a function
but you could also do that
if you pass the variable in and then out again...
You shouldn't do that either.
so how is that any different?
Can anyone shed light on these questions?
You should try to avoid using variables.
They only make your code harder for other programmers
to read, understand and maintain.
You will appreciate that when you go back
to modify code that you haven't looked at for six months --
you *will* be that other programmer.
Use constants whenever possible.
You don't need *any* variables to write useful programs.
Place a 'const' qualifier if front of every variable definition
and allow the compiler to *force* you to change it back into a variable.
Don't write functions to pass pointers or references to variables.
Pass by value, const pointer or const reference
and return an object by value instead.
Consider passing a pointer or a reference
*only* for "in-place" operations such as operations
on the elements of a *container* object
like a long list or a large array.
Global constants are good.
Old C programmers used C preprocessor macros to define constants
in header files which could be included in every translation unit.
These macros have become obsolete with the introduction
of the 'const' qualifier.
Global constants, on the other hand, break modularity.
Global constants make the code harder to maintain
because the programmers must consider the impact
of any change of a global variable on every other function
called by the program and, unless they are the original author,
they will be obliged to inspect, analyse and understand
every other function that references the global variable.
Global variables make functions harder to reuse
in other programs because they depend upon other functions
that reference and modify the global
which may have nothing to do with the new program
or that conflict with the new program.
Global variables are *never* necessary.
They may appear to be convenient at first
but they eventually cause problems
which lead new programmers to regret every considering using them.