3

According to https://learn.microsoft.com/en-us/cpp/cpp/constexpr-cpp?view=vs-2019

"constexpr indicates that the value, or return value, is constant and, if possible, is computed at compile time."

Additionally, Difference between constexpr and static constexpr global variable

"On variable declarations, constexpr implies const, and a const variable at namespace scope has internal linkage by default (so adding static does not change anything)."

Which I think means that constexpr implies const which implies static.

However, the answer for this question confuses me: When and why would you use static with constexpr?

It states that

  1. "constexpr variables are not compile-time values"
  2. "As it seems, we can benefit from static storage duration of a static constexpr variable in some corner cases."

What am I misunderstanding?

2
  • 1
    "constexpr implies const which implies static". No. constexpr does imply const (but not, necessarily the reverse). const does not imply static. Commented Nov 11, 2019 at 4:33
  • 4
    @Peter const does imply static (i.e. internal linkage). But only in namespace scope. And exceptions apply. Commented Nov 11, 2019 at 4:39

1 Answer 1

10

What you're missing is where rigorous C++ terminology is being used and where it is not.

A constexpr variable is not a compile-time value because it is not a value. A variable is either an object or a reference to an object. Objects may contain values, but objects are not values. 42 is a value. int i = 42; creates an object named i of type int, and assigns the value 42 to that object.

The Microsoft docs are using vernacular language, not rigorous C++ terminology.

A constexpr variable defines an immutable (const) object whose initializer shall be a constant expression, and therefore the variable itself may be used in places where a constant expression is required.


Which I think means that constexpr implies const which implies static.

Remember that static is an extremely overloaded keyword in C++, which has very different meanings in different contexts. The answer you quoted was responding to a very specific use of static: for namespace-scoped variables. In that case, static is unnecessary because constexpr namespace-scoped variables default to internal linkage.

But the other answer you cited is talking about other uses of static, specifically function-static. So to boil down that statement into "const implies static" is too reductive.

Sign up to request clarification or add additional context in comments.

3 Comments

when you say namespace scope are you referring to global scope?
im pretty sure you arent but the examples provided stackoverflow.com/questions/45987571/… are all in global scope i think?
ohhhh i get it now global scope is a kind of namespace scope

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.