Loading lessons...
Constants
Constants
Some values should never change: the speed of light, the number of days in a week, the tax rate. C++ lets you lock a value with const.
const
Put const before a declaration and the variable becomes read-only. Anyone (or any later code) that tries to change it gets a compile error:
const int x = 5; // x can never change
x = 10; // ERROR: x is const
- The value is fixed at creation.
- The compiler checks that nothing ever writes to it again.
- It prevents whole classes of "who changed this?" bugs.
Why use constants?
- They make your intent clear: "this is a fixed value, by design".
- They stop accidents - code can't silently modify something important.
- A well-named constant reads better:
const double PI = 3.14159;is far clearer than a naked3.14159in a formula.
A note about qualifiers
const is a qualifier - a word that modifies how a type behaves. There are others, like volatile (tells the compiler a value may change outside the program). Qualifiers sit before or after the type; we'll meet more later.
constexpr: constants the compiler knows
constexpr (C++11) means "this is a constant whose value is known at compile time". The compiler can compute and bake the value in before the program even runs:
constexpr int daysPerWeek = 7;
For fixed values used everywhere, constexpr is often the best choice: it's fast and it guarantees the value is set at compile time.
TL;DR
constmakes a variable read-only:const int x = 5;.- Trying to change a const value is a compile error.
- Constants express intent and prevent accidental changes.
- Qualifiers like
constmodify a type's behaviour. constexpris for values known at compile time.