2.7 — Values that never change (const)

📘 Chapter 2⏱ about 1 min read✍️ Beginner friendly
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 const
Good 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 constexpr for fixed numbers you know while writing the code.
  • Use const for 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 input

No 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.

Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.