C++
constexpr
Learn to define compile-time constants with constexpr.
constexpr
constexpr indicates that a variable's value can be computed at compile time. When you write constexpr int width = 800;, the compiler computes 800 during compilation and embeds it in the executable.
The difference between const and constexpr: const only guarantees immutability (the value may be determined at runtime); constexpr guarantees both immutability and compile-time evaluability.
constexpr is used where constant expressions are required (array sizes, template parameters). The compiler can optimize better.
Using constexpr
A variable declared with constexpr must have a value the compiler can compute. So the right-hand side must be a constant expression: constexpr int area = 20 * 30; is valid because 20 * 30 is computed at compile time.
But constexpr int x = readValue(); is invalid because readValue() is called at runtime. In this case use const.
constexpr functions can also be defined: when called in a constant expression context, they run at compile time. This is common in modern C++ for performance.
Exercise Define sizes with constexpr
Above main (in the global scope), declare two constexpr int values: width with value 800 and height with value 600. Inside main, add two std::cout lines: the first prints width, the second height; end each line with std::endl.
Show example solution
#include <iostream>
// Define two sizes with constexpr
constexpr int width = 800;
constexpr int height = 600;
int main() {
// Print with std::cout
std::cout << width << std::endl;
std::cout << height << std::endl;
return 0;
}
Test yourself
-
What is the difference between constexpr and const?
- constexpr is evaluated at compile time
- const is faster
- constexpr is only for double
- const is only used in classes
Show answer
constexpr is evaluated at compile time — const may hold a runtime value.
-
Match constexpr concepts
- constexpr
- Compile-time constant
- 20 * 30
- Constant expression
- readValue()
- Runtime
- array size
- Requires constexpr
-
Compile-time constant
____ int width = 800;
Show answer
constexpr int width = 800;
Next lesson: Type conversion