constexpr and Compile-Time Computation
Compile-time evaluation
Interview Relevant: Performance optimization
constexpr
Evaluate expressions at compile time.
Code Examples
Compile-time computation with constexpr.
cpp
1// constexpr function
2constexpr int factorial(int n) {
3 return n <= 1 ? 1 : n * factorial(n - 1);
4}
5constexpr int fact5 = factorial(5); // Computed at compile time
6
7// constexpr if (C++17)
8template<typename T>
9auto getValue(T t) {
10 if constexpr (is_pointer_v<T>) {
11 return *t; // Dereference pointers
12 } else {
13 return t; // Return value directly
14 }
15}
16
17// constexpr variable
18constexpr double PI = 3.14159265359;
19constexpr int SIZE = 100;
20
21// constexpr class
22class Point {
23 int x, y;
24public:
25 constexpr Point(int x, int y) : x(x), y(y) {}
26 constexpr int getX() const { return x; }
27 constexpr int getY() const { return y; }
28};
29constexpr Point p(3, 4);
30static_assert(p.getX() == 3);
31
32// C++20: consteval - must be evaluated at compile time
33consteval int square(int n) {
34 return n * n;
35}
36// int x; cin >> x;
37// square(x); // Error! Must be compile-time constant