constexpr
keyword
The constexpr
(constant expression) keyword is used in C++. This keyword is used to declare constants or functions that can be evaluated at compile time. This means the compiler can replace calls to the constexpr function with the result of the function computed at compile time, thus improving the performance of your program.
Example:
a
andb
are not actually computed at runtime, their values (100 and 25) are hard-coded into the compiled program by the compiler.
This can lead to performance improvements in your program, as the function doesn’t actually need to be called and computed at runtime.
Note
constexpr
only works for functions whose result can be determined entirely at compile time. If the function’s result depends on runtime information (such as input from the user, a value read from a file, etc.), then it cannot be aconstexpr
function.
Constexpr vs. static?
See static for the answer.