constexpr variables
- C++ course
- Expert
- Lesson 7/47
- 5 min
Learn compile-time constants with constexpr variables.
constexpr variables
The constexpr keyword declares a variable whose value can be computed at compile time. Example: constexpr int monthsPerYear = 12;. The compiler knows this value at compile time and bakes it into the executable as a ready constant.
You can use these constants in other constexpr expressions: constexpr int monthsInDecade = monthsPerYear * 10;. Both values are known at compile time, so the product is computed at compile time and the result 120 is ready at run time.
constexpr versus const
const says a variable will not be modified later; but its value may be computed at run time: const int n = getValue(); is valid.
constexpr is stricter: the value must be computable at compile time. So constexpr int n = getValue(); compiles only if getValue is constexpr. constexpr is used where a compile-time constant is required (array size, template parameter).
Practice Define the constexpr variables
Define constexpr int monthsPerYear = 12; and constexpr int monthsInDecade = monthsPerYear * 10;. In main write std::cout << monthsInDecade;.
Starter code
#include <iostream>
// Define the constexpr variables here
int main() {
// Print the result
return 0;
}Sample solution
#include <iostream>
constexpr int monthsPerYear = 12;
constexpr int monthsInDecade = monthsPerYear * 10;
int main() {
std::cout << monthsInDecade;
return 0;
}Expected output
120
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does constexpr int x = 5; guarantee?
constexpr int x = 5;- It only works with float
- It is computed only at run time
- The variable can be modified later
- The value is known at compile time Correct answer
Explanation: constexpr declares a constant known at compile time.
2 Complete the constexpr constant
constexpr int monthsPerYear = ____;
constexpr int monthsPerYear = 12;
Explanation: Write constexpr int monthsPerYear = 12; the number of months in a year is 12.
3 Match each declaration to its trait
| Term | Meaning |
|---|---|
constexpr int x = 5; |
Compile-time constant |
const int y = getValue(); |
Run-time constant |
constexpr int z = x * 2; |
Computable constant |
int w = 7; |
Mutable variable |