constexpr specifier
The constexpr specifier declares that it is possible to evaluate the value of the function or variable at compile time.
Example
1 |
|
Try you code on compiler explorer
On the right side, the assembly code shows that the program calls accumSum(int)
function explicitly during runtime.
If we add constexpr
when declaring a
, we can see the function call does not appear in the assembly code.
const vs constexpr
- const can be deferred at runtime.
- constexpr must be evaluated at compile time. All
constexpr
variables areconst
.
1 | constexpr int x = 1; // OK |
constexpr in OOP
1 | class Base { |
References
constexpr specifier