For defining compile-time constants of integral types like the following (at function and class scope), which syntax is best?
static const int kMagic = 64; // (1)
constexpr int kMagic = 64; // (2)
(1)
works also for C++98/03 compilers, instead (2)
requires at least C++11. Are there any other differences between the two? Should one or the other be preferred in modern C++ code, and why?
EDIT
I tried this sample code with Godbolt's CE:
int main()
{
#define USE_STATIC_CONST
#ifdef USE_STATIC_CONST
static const int kOk = 0;
static const int kError = 1;
#else
constexpr int kOk = 0;
constexpr int kError = 1;
#endif
return kOk;
}
and for the static const
case this is the generated assembly by GCC 6.2:
main::kOk:
.zero 4
main::kError:
.long 1
main:
push rbp
mov rbp, rsp
mov eax, 0
pop rbp
ret
On the other hand, for constexpr
it's:
main:
push rbp
mov rbp, rsp
mov DWORD PTR [rbp-4], 0
mov DWORD PTR [rbp-8], 1
mov eax, 0
pop rbp
ret
Although at -O3
in both cases I get the same (optimized) assembly:
main:
xor eax, eax
ret
EDIT #2
I tried this simple code (live on Ideone):
#include <iostream>
using namespace std;
int main() {
const int k1 = 10;
constexpr int k2 = 2*k1;
cout << k2 << '\n';
return 0;
}
which shows that const int k1
is evaluated at compile-time, as it's used to calculate constexpr int k2
.
However, there seems to be a different behavior for double
s. I've created a separate question for that here.
The principal difference between const and constexpr is the time when their initialization values are known (evaluated). While the values of const variables can be evaluated at both compile time and runtime, constexpr are always evaluated at compile time.
So you should definitely use static constexpr in your example. However, there is one case where you wouldn't want to use static constexpr . Unless a constexpr declared object is either ODR-used or declared static , the compiler is free to not include it at all.
In Conclusion. constexpr is an effective tool for ensuring compile-time evaluation of function calls, objects and variables. Compile-time evaluation of expressions often leads to more efficient code and enables the compiler to store the result in the system's ROM.
A constexpr integral value can be used wherever a const integer is required, such as in template arguments and array declarations. And when a value is computed at compile time instead of run time, it helps your program run faster and use less memory.
constexpr
variable is guaranteed to have a value available at compile time. whereas static const
members or const
variable could either mean a compile time value or a runtime value. Typing constexpr
express your intent of a compile time value in a much more explicit way than const
.
One more thing, in C++17, constexpr
static data member variables will be inline too. That means you can omit the out of line definition of static constexpr
variables, but not static const
.
As a demand in the comment section, here's a more detailed explanation about static const
in function scope.
A static const
variable at function scope is pretty much the same, but instead of having a automatic storage duration, it has static storage duration. That mean it's in some way the equivalent of declaring the variable as global, but only accessible in the function.
It is true that a static
variable is initialize at the first call of the function, but since it's const
too, the compiler will try to inline the value and optimize out the variable completely. So in a function, if the value is known at compile time for this particular variable, then the compiler will most likely optimize it out.
However, if the value isn't known at compile time for a static const
at function scope, it might silently make your function (a very small bit) slower, since it has to initialize the value at runtime the first time the function is called. Plus, it has to check if the value is initialized each time the function is called.
That's the advantage of a constexpr
variable. If the value isn't known at compile time, it's a compilation error, not a slower function. Then if you have no way of determine the value of your variable at compile time, then the compiler will tell you about it and you can do something about it.
As long as we are talking about declaring compile-time constants of scalar integer or enum types, there's absolutely no difference between using const
(static const
in class scope) or constexpr
.
Note that compilers are required to support static const int
objects (declared with constant initializers) in constant expressions, meaning that they have no choice but to treat such objects as compile-time constants. Additionally, as long as such objects remain odr-unused, they require no definition, which further demonstrates that they won't be used as run-time values.
Also, rules of constant initialization prevent local static const int
objects from being initialized dynamically, meaning that there's no performance penalty for declaring such objects locally. Moreover, immunity of integral static
objects to ordering problems of static initialization is a very important feature of the language.
constexpr
is an extension and generalization of the concept that was originally implemented in C++ through const
with a constant initializer. For integer types constexpr
does not offer anything extra over what const
already did. constexpr
simply performs an early check of the "constness" of initializer. However, one might say that constexpr
is a feature designed specifically for that purpose so it fits better stylistically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With