C++
constexpr
Compile-time constants and computation.
By EZ4Code Team
constexprcompile-time
Code
#include <iostream>
#include <array>
// constexpr function
constexpr int factorial(int n) {
return n <= 1 ? 1 : n * factorial(n - 1);
}
// constexpr variable
constexpr int max_size = 256;
// constexpr class (C++20)
struct Point {
int x, y;
constexpr Point(int x, int y) : x(x), y(y) {}
constexpr int sum() const { return x + y; }
};
// consteval: must execute at compile time (C++20)
consteval int square(int n) {
return n * n;
}
// Compile-time Fibonacci
constexpr int fib(int n) {
if (n <= 1) return n;
int a = 0, b = 1;
for (int i = 2; i <= n; ++i) {
int tmp = a + b;
a = b;
b = tmp;
}
return b;
}
int main() {
// Compile-time computation
constexpr int f5 = factorial(5);
std::cout << "5! = " << f5 << "\n";
// Used for array size
std::array<int, factorial(3)> arr;
std::cout << "array size: " << arr.size() << "\n";
// constexpr object
constexpr Point p(3, 4);
static_assert(p.sum() == 7);
// Compile-time vs runtime
int n = 5;
int runtime_f = factorial(n); // Runtime
constexpr int compile_f = factorial(5); // Compile-time
std::cout << "fib(10) = " << fib(10) << "\n";
std::cout << "square(7) = " << square(7) << "\n";
return 0;
}Explanation
constexpr allows compile-time computation; consteval forces compile-time execution, improving runtime performance.