The constexpr
keyword, short for constant expression, was a feature introduced in C++11 that allows the value of an expression to be evaluated at compile-time.
This feature significantly increases performance since the expression does not need to be computed again during runtime; instead, its value can simply be used where needed.
There are three main applications of constexpr
:
constexpr
variablesThe value of a variable can be computed at compile-time by making it constexpr
:
constexpr int num1 = 20;
constexpr int num2 = num1 * 10;
// Both are evaluated at compile-time
The variables num1
and num2
are implicitly const
. A constexpr
variable has to be initilized with an expression. This expression can only contain literals or other constexpr
variables.
constexpr
functionsconstexpr
functions are executed and evaluated during compilation.
A constexpr
function must follow the rules below:
Its return type cannot be void
, i.e., it must compute and return a value.
It can only call other constexpr
functions.
It can only refer to global const
variables.
Here is an example:
#include <iostream>using namespace std;constexpr bool is_even(int num){if(num % 2 == 0){return true;}return false;}int main() {constexpr int n = 30;constexpr bool check_even = is_even(n); // Evaluated at compile-timecout << check_even << endl;}
The value of check_even
is evaluated at compile-time. If this value is to remain constant throughout the program, having it computed at compile-time is better than computing it at runtime whenever it is required.
constexpr
objectsThese objects are initialized at compile-time. A constexpr
object can be created by following these rules:
The constructor must be constexpr
.
All non-static members must be initialized. Furthermore, they must have constexpr
constructors themselves, e.g., basic data types.
The constructor must be defined as default
or delete
; otherwise, its body must be empty.
Object methods can also be declared constexpr
as long as they follow the rules for constexpr
functions.
A constexpr
object has been created below:
#include <iostream>using namespace std;class Coordinate {int x;int y;public:// constexpr constructorconstexpr Coordinate(int x_c, int y_c): x(x_c), y(y_c){}// constexpr methodconstexpr int get_x(){return x;}constexpr int get_y(){return y;}};int main() {Coordinate c = Coordinate(5, 10); // Object created at compile-timeint x = c.get_x();int y = c.get_y(); // Coordinates retrieved at compile-timecout << x << ", " << y << endl;}
Free Resources