Using Global Variables
A global variable is a variable with a global scope. The set of global variables are
known as the global environments or global state. Global variables are used to pass
information between sections of codes that do not share the same caller/callee relations
like threads and signal handlers. Without a proper locking code using the global variables
will not be thread-safe except for read only values.
For programs, it is best to put your global variable declarations at the
top/beginning. This way, you can see, in one place, the names of variables that will be
referenced across procedure boundaries.
Here is a list of the attributes of global variables.
Global variables are containers whose contents can be accessed anywhere in a program, are declared with the global command, get assigned a value when a make command is interpreted, and maintain a value until changed with another make command. In some languages, all variables are global. In most languages, the variables have
a limited scope. The way that you can declare a variable is at the top of the programming
level. In other languages, however, global variables do not exist. Those languages use
modular programming languages that enforce a module structure.
Normally, if a global variable is going to be used in more than 2 files, it’s better to
use the header file approach. Some programmers place all of a programs global variables
in a file called globals.cpp, and create a header file named global to be included by other
.cpp files that need to use them. New programmers are often tempted to use lots of global
variables, because they are easy to work with, especially when many functions are
involved. It is recommended that they do not relay on that for programing and to use other resources.
Global variables make every function call potentially dangerous. The programmer
does not have a way to know which environments are dangerous and which ones are not.
It is better for a programmer to focus on a local variable because they are much safe and
the programmer has no easy way of knowing which ones are dangerous and which ones
aren’t! Local variables are much safer because other functions can not affect them
directly.
References:
William Wulf and Mary Shaw, “Global Variable Considered Harmful”, ACM SIGPLAN Notices, volume 8, issue 2, 1973 February, pp. 28–34.