constexpr and Compile-Time
Compute values at compile time.
What constexpr Means
constexpr tells the compiler a value or function can be evaluated at compile time, producing a true compile-time constant.
#include <iostream>
int main() {
constexpr int size = 4 * 4; // computed at compile time
int arr[size];
std::cout << sizeof(arr) / sizeof(int) << "\n";
}constexpr Functions
A constexpr function can run at compile time when given constant arguments, and at runtime otherwise.
#include <iostream>
constexpr int square(int x) { return x * x; }
int main() {
constexpr int s = square(5); // compile time
int n = 6;
std::cout << s << " " << square(n) << "\n"; // second at runtime
}All lessons in this course
- const Variables and Parameters
- const Member Functions
- constexpr and Compile-Time
- consteval and constinit