Global Variables
Variables and constants can be declared outside of functions and procedures, within the program itself. Variables declared in this way are called global variables. It may seem tempting to use global variables to share values between functions and procedures, but this is a bad idea. Global variables should be avoided, and for many problems are unnecessary.
The issue with global variables is that their values can be changed from anywhere within the program’s code. This can make it difficult to locate the source of errors when global variables are used in larger programs. There are some cases where you will need to use global variables, but you should always have looked for several ways not to before accepting that you really do need them.
While global variables should be avoided, constants should be declared globally. The value of a constant cannot change, so the issues with global variables do not apply. Global constants actually help ensure that values remain consistent throughout the program. As a result, most constants generally end up being global.
In C/C++
Example
Reading through the above code, look at main, and try to answer the following questions:
- What does the program output to the terminal?
- What is the value of
x
when the program completes?
Answers
- Program output:
- Value of
x
at program completion: 13.
Is this what you expected?
Would it be easy to understand how x
was being changed in this program?
We would argue definitely not!
This is an issue that only gets worse as the size and complexity of a program increases.