constexpr vs. static const: Which one to prefer?

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.

Leave a Comment