The dangers of global variables
What you'll learn: Why relying on variables accessible from anywhere in your code can lead to unpredictable bugs and "spaghetti code."
The communal fridge problem
Imagine you live in a large apartment building with a single communal fridge in the lobby. Anyone can put food in, take food out, or change the labels. One morning, you put your sandwich in a blue box. Ten minutes later, you go to grab it, but it’s gone. Or worse, someone replaced your turkey sandwich with a brick. Because everyone has access, you can never be sure who changed the state of the fridge or when it happened.
In C, a global variable is that communal fridge. It is declared outside of any function, making it accessible to every single part of your program. While this seems convenient, it creates a "hidden web" of connections that makes your code fragile.
When code becomes unpredictable
When you use global variables, functions stop being independent tools. Instead, they become dependent on the "mood" of the rest of the program.
#include <stdio.h>
// A global variable
int speed = 50;
void cruise_control() {
// This function assumes 'speed' hasn't been changed elsewhere
if (speed > 60) {
printf("Slowing down...\n");
}
}
void emergency_system() {
// A completely different part of the code changes the global state
speed = 0;
}
int main() {
cruise_control();
emergency_system();
// Now any other function using 'speed' will behave differently!
return 0;
}
In the example above, if emergency_system() runs, every other function using speed is suddenly affected. In a program with thousands of lines, tracking down which function accidentally changed a global variable is like trying to find a needle in a haystack.
Why to avoid them
- Hard to Debug: If a global variable has the wrong value, any function in your file could be the culprit.
- Naming Collisions: You might accidentally use the same name for a local variable, leading to "shadowing" and confusion.
- Lack of Thread Safety: If two parts of a program try to change a global variable at the exact same millisecond, the program might crash.
Always prefer local variables (declared inside functions). They are like your personal lunchbox: only you know what's inside, and only you can change it.
Key takeaway
Global variables make code hard to track and debug; keep variables local to the functions that need them to ensure your code remains predictable.