 |
Department of Engineering |
 |
 |
C++: Global warning
Programmers are often warned about using global variables (variables which are
outside functions and classes). Here are
some reasons why.
System include files
On my machine, the following code doesn't compile.
#include <iostream>
int acct;
int main()
{
int i;
}
However, the following does -
int acct;
int main()
{
int i;
}
and so does
#include <iostream>
int main()
{
int acct;
int i;
}
Why?
The error message when compiling the first program says
foo.cc:2: error: int acct redeclared as different kind of symbol
/usr/include/unistd.h:837: error: previous declaration of int acct(const char*)
so it seems that using #include <iostream> causes /usr/include/unistd.h
to be read, which happens to mention a routine called acct - in fact
the offending line is
extern int acct (__const char *__name) throw ();
Using global variables risks name clashes like this. The 3rd example compiles
because the acct variable in main isn't global.
Namespaces
It's common to have
using namespace std;
at the top of a file. This makes available the visible names in the std
namespace so you can do things like
cout << "test" << endl;
It's safer not to use using namespace std; and instead type
std::cout << "test" << std::endl;
By doing this you don't bring into view all the std
namespace names and you reduce the risk of name clashes.
More Safety
If you make a mistake when writing code you want to know as soon as possible - at compile time rather than run time. If you have lots of globals you risk
creating unnecessary run-time errors. The example below is rather artificial,
but in bigger programs I've seen the practical consequences of this approach.
int i1, i2; // I1 and I2
int main () {
int il=0; // IL
i1=i1+7; // I1
}
In this program, the programmer meant to write "il=il+7" ("IL=IL+7") rather than
"i1=i1+7" ("I1=I1+7") . Unfortunately, the typing error doesn't cause a compilation
error because "i1" exists as a global.
Again, having as few global names visible as possible increases the
chances of producing a successful program.
Naming Rules
Some names are reserved for use by the compiler/libraries. Don't
use
- C++ keywords (for, auto, etc)
- names that contain a double underscore - you might get away with it, but why take a chance?
- names that begin with an underscore followed by an uppercase letter
Names that begin with an underscore followed by a lowercase letter are
safe to use as long as they're not global.