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.
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.
Why Global State Is Dangerous
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.
The Two Core Rules
Global vs. Local Data Flow
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 int x = 5;Value cannot be reassigned after initialization.
const std::string& sPass by reference without risk of modification.
int getX() const;Promise that the method won't modify the object.
How to Apply These Rules
Example 1: Before (Global State)
Example 1: After (Local + Const)
Example 2: Const References
Example 3: Const Member Functions
Common Mistakes
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?
class Counter {
int count_;
public:
void increment() { count_++; }
int getCount() { return count_; }
void reset() { count_ = 0; }
};
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?
const int x = 10;
x = 20;
std::cout << x;