Loading lessons...
Global Variables
Global Variables
A global variable is declared outside any function. It is born when the program starts and lives until the program ends.
How to declare one
int playerScore = 0; // global
int addPoints(int n) {
playerScore += n; // any function can touch it
return playerScore;
}
Because it's global, playerScore is visible and writable from every function in the file. Any function, any time.
The lifespan
Globals have static storage duration: they are created before main runs and destroyed only when the program exits. They never "go away" mid-program the way locals do.
Why (non-const) globals are discouraged
They're often called evil in C++ circles, and there are real reasons:
- Hard to reason about: any function in the file can change a global. To understand its value, you must check every function - not just the code in front of you.
- Hidden connections: functions stop being independent. Two functions that don't call each other can still secretly depend on the same global.
- Reordering bugs: the order functions run changes the outcome, so moving a call around changes behavior.
int counter = 0;
void a() { counter += 1; } // who knows what a() does to the rest of the program?
void b() { counter *= 2; }
When globals are okay
- Constants are fine:
const int MAX_PLAYERS = 4;can't be changed, so it can't cause surprises. - Small amounts of program-wide state that never changes are acceptable.
- For mutable shared state, prefer passing values into functions as parameters.
TL;DR
- A global is declared outside all functions and lives for the whole program.
- Its lifespan: created before
main, destroyed at exit (static storage duration). - Mutable globals are discouraged: hard to reason about, hidden connections.
- Functions sharing globals secretly depend on each other.
- Constants as globals are great; mutable globals are not.