2.7 — Values that never change (const)
Read one box at a time. No rush.
const#
Some values should never change. Add const and C++ will stop anyone (including you!) from changing it.
C++
const double pi { 3.14159 };const int maxLives { 3 }; maxLives = 5; // error: maxLives is constGood habit
If a value should not change, make it const. It prevents bugs and tells readers "this stays the same".
constexpr#
constexpr is like const, but stronger: the value must be known before the program runs (when compiling).
C++
constexpr int daysInWeek { 7 };constexpr double gravity { 9.81 };- Use
constexprfor fixed numbers you know while writing the code. - Use
constfor values that come from the user or are worked out while running.
C++
int age {};std::cin >> age;const int ageNextYear { age + 1 }; // const, not constexpr — depends on inputNo magic numbers#
A magic number is a number in the code with no explanation.
C++ — wrong ✗
int total { price * 1.2 };C++ — right ✓
constexpr double taxRate { 1.2 };double total { price * taxRate };Now the reader knows what 1.2 means, and you only need to change it in one place.
Tip: press ← / → to move between lessons, / to search.