Global Variable - C and C++

C and C++

The C language does not have a global keyword. However, variables declared outside a function implicitly have a scope covering everything in the .c file or compilation unit containing its declaration. In a small program contained in a single file, such variables effectively have global scope. On the other hand, a variable that is required to have global-scope in a multi-file project needs to be imported individually into each file using the extern keyword. Such global access can be made implicit by placing the extern declaration in a shared header file, since it is common practice for all .c files in a project to include at least one .h file: the standard header file errno.h is an example, making the errno variable accessible to all modules in a project. Where this global access mechanism is judged problematic, it can be disabled using the static keyword which restricts a variable to file scope, and will cause attempts to import it with extern to raise a compilation error.

An example of a "global" variable in C:

/* Note that this example is correct. global does not qualify as a global variable as it is not "in scope everywhere". */ #include int myGlobal = 3; /* This is the external variable. */ static void ChangeMyGlobal(void) { myGlobal = 5; /* Reference to external variable in a function. */ } int main(void) { printf("%d\n", myGlobal); /* Reference to external variable in another function. */ ChangeMyGlobal; printf("%d\n", myGlobal); return 0; }

As the variable is an external one, there is no need to pass it as a parameter to use it in a function besides main. It belongs to every function in the module.

The output will be:

3 5

The use of global variables makes software harder to read and understand. Since any code anywhere in the program can change the value of the variable at any time, understanding the use of the variable may entail understanding a large portion of the program. They make separating code into reusable libraries more difficult because many systems (such as DLLs) don't directly support viewing global variables in other modules. They can lead to problems of naming because a global variable makes a name dangerous to use for any other local or object scope variable. A local variable of the same name can shield the global variable from access, again leading to harder to understand code. The setting of a global variable can create side effects that are hard to understand and predict. The use of globals make it more difficult to isolate units of code for purposes of unit testing, thus they can directly contribute to lowering the quality of the code.

Read more about this topic:  Global Variable