90

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.

Community
  • 1
  • 1
Mr.C64
  • 41,637
  • 14
  • 86
  • 162
  • 2
    I prefer the `constexpr` approach. It is *explicit*, and *strong*. Anyway, the other alternative is not same, from linkage point of view as well: If you put `const` (or `static`, or both), it makes the variable to have *internal* linkage. So they're semantically different. – Nawaz Dec 13 '16 at 16:15
  • 2
    Which one to prefer depends on what you're going to use them for. As @Nawaz says, those two examples do different things, and without any mention of their intended uses it's impossible to decide which is "better". – Pete Becker Dec 13 '16 at 16:17
  • @PeteBecker: I'm going to just use them for ordinary compile-time named constants instead of using "magic numbers", think e.g. of error codes or compile-time constant dimensions for drawing something, etc. – Mr.C64 Dec 13 '16 at 16:19
  • 1
    At what scope do you define them? – HolyBlackCat Dec 13 '16 at 16:20
  • @HolyBlackCat: I'm interested at both the function scope level and class member level. – Mr.C64 Dec 13 '16 at 16:22
  • For the magic numbers i prefer enums. Enums give you the literal-like behavior, while neither constexpr nor static const do. – SergeyA Dec 13 '16 at 16:24
  • In fact, `constexpr` is very usefull when you use template because template needs to be evaluated at compile time. So if you are creating some libraries or are using template, use constexpr is essential, otherwise, you can simply use const. – Yves Dec 13 '16 at 16:32
  • @Thomas: Please read my question. I'm not asking "constexpr" vs. "const", but vs. "static const". – Mr.C64 Dec 13 '16 at 16:33
  • 1
    @Mr.C64 When you are creating some class, which will be used as a parameter of template, here is the good time to use constexpr: all members are constexpr, whereas `static const` can't do this. ---- This is what I was trying to say. – Yves Dec 13 '16 at 16:42
  • 3
    The GCC assembly in your edit proves nothing. – Nawaz Dec 13 '16 at 16:58
  • 1
    @Nawaz: I don't want to prove anything, except that maybe the optimizer is smart enough ;) I was *asking* (and _experimenting_) to try to better learn. – Mr.C64 Dec 13 '16 at 17:00
  • @Nawaz In contexts where `const` implies internal linkage, so does `constexpr`. The test is whether the type is (non-volatile) const-qualified, not the keyword used. – T.C. Dec 13 '16 at 22:24
  • @T.C. that changes in C++17; a `constexpr` object at namespace scope will have external linkage unless declared `static` – M.M Dec 14 '16 at 04:06
  • @M.M [It doesn't.](https://timsong-cpp.github.io/cppwp/basic.link#3.2) `constexpr` doesn't imply `inline` for variables at namespace scope. – T.C. Dec 14 '16 at 04:13
  • @T.C. OK. P0386R0 said "A function or variable declared with the constexpr specifier is implicitly an inline function or variable", but I see that N4606 changed "variable" to "static data member" in that sentence – M.M Dec 14 '16 at 07:50
  • @T.C. can you comment/answer on [this question](http://stackoverflow.com/questions/41133290/) ? OP accepted my answer but I'm not sure what the status of it will be in C++17 – M.M Dec 14 '16 at 07:53
  • @M.M [R2](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0386r2.pdf) is the one voted in. – T.C. Dec 14 '16 at 08:45
  • one thing to keep in mind is that constexpr doesn't work in visual studio 2012. using enums for constants that are intended to be inlined but not quite macros allows better portability. – Dmytro Nov 12 '17 at 22:15

2 Answers2

75

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.

Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141
  • I'm not asking "constexpr" vs. "const", but vs. *static* const. Isn't "static const" compile-time like "constexpr"? – Mr.C64 Dec 13 '16 at 16:33
  • @NathanOliver: Good point. If it's a `static const` class member, however, I think it's usable in a constant expression, though. – AndyG Dec 13 '16 at 16:38
  • @NathanOliver: Very good point. Please add that as answer to 1) get better answer visibility and 2) get deserved points (I'll upvote). – Mr.C64 Dec 13 '16 at 16:40
  • @AndyG Yes as a class member it is usable as it has to be defined at compile time. – NathanOliver Dec 13 '16 at 16:41
  • 2
    @Mr.C64: The keyword `static` has **nothing** to do with compile-time *const-ness* or *computability*. At namespace-level, it affects the linkage; in the class-scope, it makes the member *common* to all instances; and in function-scope, it makes the variable to *persist* between calls. – Nawaz Dec 13 '16 at 16:49
  • @Nawaz: I know that about `static`, but I thought that `static` could be used as a hint for the C++ compiler to optimize considering the `static const` variable as a compile-time constant. At least, before C++11's `constexpr`, `static const` was used (as an approximation?) for compile-time constants. – Mr.C64 Dec 13 '16 at 16:58
  • 1
    @Mr.C64: The point is, `static const` could be compile-time constant, does **not** mean it *has to be*. – Nawaz Dec 13 '16 at 17:00
  • @Mr.C64 See my edit, I added a more detailed explanation about static const. – Guillaume Racicot Dec 13 '16 at 17:03
  • 6
    Ad the "little bit slower" part: not only because it has to initialize the value the first time the function is called, but it also has to determine at run time at every call *whether* that is the first time it is called. This is not trivial, see https://godbolt.org/g/wBejUj – The Vee Dec 13 '16 at 17:16
  • "`static constexpr` variables will be inline too" is misleading. `constexpr` implies `inline` only for static data members (and functions), not all variables. – T.C. Dec 13 '16 at 22:26
  • @Guillaume Racicot: `static const int` member of a class initialized with constant expression is guaranteed to act as an Integral Constant Expression, i.e. be a compile-time constant. It does not require a deparate definition as long as it is not odr-used anywhere in the code. As long as we are talking about rvalue contexts, there's no difference between a `constexpr int` constant and `static const int` constant. (The same applies to `const int` objects in local scope.) The difference is purely stylistic. – AnT stands with Russia Dec 13 '16 at 23:05
  • Also, C++ language prohibits dynamic initialization for local `static` objects of scalar types initialized with constant expressions, meaning that such object cannot make your function slower. – AnT stands with Russia Dec 13 '16 at 23:09
  • @AnT static constexpr data members are different in c++17. They can be odr used without an out of line definition since they are unlined by default. Whereas static const must have an out of line definition to be odr used. – Guillaume Racicot Dec 13 '16 at 23:09
  • @Guillaume Racicot: Yes, but that's a different topic. It applies to "lvalue uses" of such objects. Meanwhile, the topic we are discussing appears to be concerned with the matter of defining *compile-time constants*. – AnT stands with Russia Dec 13 '16 at 23:12
  • @The Vee: The compilers are not allowed to do that if the static object has scalar type and is initialized with constant expressions. Constant initialization (as opposed to dynamic initialization) is mandated by the language in such cases. – AnT stands with Russia Dec 13 '16 at 23:18
  • @AnT Absolutely. But my comment was an extension to this particular paragraph in the answer: "However, if the value isn't known at compile time for a static const at function scope"... – The Vee Dec 13 '16 at 23:31
44

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.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
  • 2
    Thanks for your answer. BTW It [seems](http://stackoverflow.com/q/41141734/1629821) that `double` gets a different treatment than `int` regarding initializing `constexpr` with `const` (but not in MSVC). – Mr.C64 Dec 14 '16 at 13:12
  • @Mr.C64: Yes, it is. I was wrong to use the term "scalar" types in my answer. The full "compile time constant" treatment is only applied to `const` objects of integral or enum types. – AnT stands with Russia Dec 14 '16 at 15:19
  • Thanks. Another reason to prefer `constexpr`. – Mr.C64 Dec 14 '16 at 15:27
  • "rules of constant initialization prevent local `static const int` objects from being initialized dynamically" - you mean IF the initializer is a constant expression, right? – aschepler Aug 04 '17 at 11:52
  • It's not really exactly the same is it? If you make a variable constexpr it will be initialized on compile time, so that will increase compilation time, but will make run time faster? – Vegeta Oct 12 '20 at 13:28