Advertisement
Beginner C++, Constexpr & Compile-Time

What does constexpr mean?

Short answer

constexpr indicates that a value or function can be evaluated at compile time. A constexpr variable is a compile-time constant; a constexpr function can be evaluated at compile time when given constant arguments (and at run time otherwise).

Save C++ mock interview
Advertisement
AModel answer
constexpr indicates that a value or function can be evaluated at compile time. A constexpr variable is a compile-time constant; a constexpr function can be evaluated at compile time when given constant arguments (and at run time otherwise). It enables computations to move from run time to compile time, improving performance and enabling constant expressions.
constexpr int square(int x) { return x * x; }
constexpr int n = square(5);  // computed at compile time
Real-world example
A constexpr function computes a lookup table at compile time so no runtime cost is incurred.
Likely follow-ups
  • Can a constexpr function run at run time? | What is a constant expression?
Related topics