01 / 20

Minimizing Global State
& Const Correctness

Learn to write safer, more predictable C++ by reducing global variables and using const to protect your data from accidental modification.

C++

What Is Global State?

Global state refers to any variable declared outside of all functions and classes. It can be read and modified by any part of your program, at any time, without restriction.

// This is global state int playerScore = 0; std::string currentLevel = "menu"; void addPoints(int pts) { playerScore += pts; // modifies global } void resetGame() { playerScore = 0; // also modifies global currentLevel = "menu"; }

Why Global State Is Dangerous

✕ Hidden Dependencies
Functions secretly depend on and modify shared data, making the code hard to understand.
✕ Hard to Test
Tests interfere with each other because they share the same global variables.
✕ Unpredictable Order
When multiple functions modify globals, the result depends on call order: a major source of bugs.

What Is Const Correctness?

Const correctness means using the const keyword wherever a value should not be modified. It turns the compiler into a guardian that prevents accidental changes at compile time.

const double PI = 3.14159265; const int MAX_PLAYERS = 4; PI = 3.0; // COMPILER ERROR! Cannot modify const

The Two Core Rules

1
Minimize global state: Pass data through function parameters and return values instead of storing it in global variables.
2
Use const by default: Mark every variable, parameter, and member function const unless you have a specific reason to mutate it.

Global vs. Local Data Flow

Global State (Bad) g_score funcA() funcB() funcC() Everyone reads & writes Parameters (Good) main() addPts(s, p) display(s) reset() Data flows via params & returns

const vs. Non-const

const Non-const
Can be modified? No: compiler enforces Yes: by any code
Intent clarity High: reader knows it won't change Low: might change anywhere
Bug surface Smaller: fewer things can go wrong Larger: any mutation is possible
Optimization Better: compiler can optimize Limited: must assume changes

Where to Apply const

const Variables
const int x = 5;
Value cannot be reassigned after initialization.
const References
const std::string& s
Pass by reference without risk of modification.
const Methods
int getX() const;
Promise that the method won't modify the object.

How to Apply These Rules

1
Identify global variables in your code. Ask: does this truly need to be accessible everywhere?
2
Move data into local scope. Pass it as a parameter to functions that need it.
3
Mark everything const. Start with const on every new variable. Remove it only if the compiler complains and you intended to mutate.
4
Use const references for function parameters that should not be changed (especially strings and objects).
5
Mark member functions const if they only read from the object (getters, display functions).

Example 1: Before (Global State)

// BAD: global state int total = 0; void addItem(int price) { total += price; } void applyDiscount(double pct) { total *= (1.0 - pct); } int main() { addItem(50); applyDiscount(0.1); // Who changed total? When? Hard to trace. }

Example 1: After (Local + Const)

// GOOD: no global state, const where possible int addItem(const int currentTotal, const int price) { return currentTotal + price; } double applyDiscount(const int total, const double pct) { return total * (1.0 - pct); } int main() { const int total = addItem(0, 50); const double final = applyDiscount(total, 0.1); }

Example 2: Const References

// BAD: copies the entire vector + no const void printAll(std::vector<std::string> names) { for (int i = 0; i < names.size(); i++) std::cout << names[i] << "\n"; } // GOOD: const reference, no copy, can't modify void printAll(const std::vector<std::string>& names) { for (const auto& name : names) std::cout << name << "\n"; }

Example 3: Const Member Functions

class Rectangle { double width_, height_; public: Rectangle(double w, double h) : width_(w), height_(h) {} // const: promises not to change the object double area() const { return width_ * height_; } // non-const: actually modifies the object void scale(const double factor) { width_ *= factor; height_ *= factor; } };

Common Mistakes

✕ "Just One Global"
One global grows into many. Every global you add makes the next one feel more acceptable.
✕ Forgetting const&
Passing large objects by value copies them needlessly. Always use const& for read-only parameters.
✕ Casting Away const
Using const_cast to remove const defeats the entire purpose. If you need it, redesign instead.

Summary Comparison

Poor Practice Best Practice
Data storage Global variables Local variables + parameters
Mutability Everything is mutable const by default
Parameter passing Pass by value (copies) const reference
Member functions None marked const Getters/observers are const
Testability Tests interfere with each other Each test is isolated

Question 1 of 5

What is the main danger of using global variables in a large C++ program?

Question 2 of 5

Which function signature correctly uses const correctness for a read-only parameter?

Question 3 of 5

Given the class below, which method should be marked const?

Question 4 of 5

What is the best way to replace a global variable that multiple functions need?

Question 5 of 5

What does the following code produce?