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 doubles. I've created a separate question for that here.
constexprapproach. It is explicit, and strong. Anyway, the other alternative is not same, from linkage point of view as well: If you putconst(orstatic, or both), it makes the variable to have internal linkage. So they're semantically different.