C++ › Constexpr & Compile-Time

What is the difference between const and constexpr?

Beginner

Answer

const means the value won't change after initialization but it may be initialized at run time. constexpr means the value is a compile-time constant and must be initializable at compile time. All constexpr objects are const, but not all const objects are constexpr. Use constexpr when you need a true compile-time constant.
const int a = getValue();   // runtime init, immutable
constexpr int b = 10 * 5;   // compile-time constant
Real-world example An array size must be constexpr, so a const initialized from a runtime call can't be used for it.

Common follow-ups: Is every constexpr also const? | When must you use constexpr over const?