Introduction to Global Variables
Global variables are accessible from any part of the program, but they are often discouraged due to potential issues. The focus is usually on non-const global variables.
The Problem with (non-const) Global Variables
- The biggest issue is their ability to be changed by any function leading to unpredictable program state.
- Example: Changing a global variable without the programmer's knowledge can lead to unexpected outcomes.
int g_mode;
void doSomething() {
g_mode = 2;
}
int main() {
g_mode = 1;
doSomething();
if (g_mode == 1) {
// Programmer expects g_mode to be 1, but it's changed to 2
std::cout << "No threat detected.\n";
} else {
std::cout << "Launching nuclear missiles...\n";
}
return 0;
}
Drawbacks of (non-const) Global Variables
- Debugging challenges: Locating all places where a global variable is modified can be difficult.
- Reduced modularity: Global variables make the program less modular and flexible.
- Difficulty in understanding: The usage of global variables may require examining the entire program.
Best Practice: Avoid (non-const) Global Variables:
- The advice is to use local variables instead of global variables whenever possible.
- Global variables should only be used if there's a single instance of what the variable represents.