constexpr functions
- C++ course
- Expert
- Lesson 8/47
- 5 min
Learn to write constexpr functions.
constexpr functions
A constexpr function is a function that can be evaluated at compile time. When called with all constant-expression arguments, the result is computed at compile time. Example: constexpr int square(int x) { return x * x; }.
The call constexpr int s = square(5); produces 25 at compile time. But int n = readInput(); int r = square(n); runs at run time; constexpr here only allows it, it does not force it. Flexibility is the power of constexpr.
C++14 extensions
Since C++14, constexpr functions may contain loops, local variables and if. In C++11 only a single return statement was allowed.
Example: constexpr int factorial(int n) { int r = 1; for (int i = 2; i <= n; ++i) r *= i; return r; }. This body is valid in C++14 and later; when called with a constant argument, the compiler unfolds the loop at compile time.
Practice Write the constexpr square function
Write constexpr int square(int x) with body return x * x;. In main define constexpr int s = square(7); and write std::cout << s;.
Starter code
#include <iostream>
// Define the constexpr square function here
int main() {
// Define s and print it
return 0;
}Sample solution
#include <iostream>
constexpr int square(int x) {
return x * x;
}
int main() {
constexpr int s = square(7);
std::cout << s;
return 0;
}Expected output
49
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the function body
constexpr int square(int x) { return x * ____; }
constexpr int square(int x) { return x * x; }
Explanation: Write return x * x;; the multiplier for square is x itself.
2 When is a constexpr function evaluated at compile time?
constexpr int square(int x) { return x * x; }- When arguments are constant expressions Correct answer
- Only if it is inline
- Always
- Only inside templates
Explanation: With constant arguments it runs at compile time; with variable arguments at run time.
3 Match each call to its result
| Term | Meaning |
|---|---|
square(5) |
returns 25 |
square(7) |
returns 49 |
square(10) |
returns 100 |
square(0) |
returns 0 |