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?

csguy
  • 1,354
  • 2
  • 17
  • 37
  • 1
    "`constexpr` implies `const` which implies `static`". No. `constexpr` does imply `const` (but not, necessarily the reverse). `const` does not imply `static`. – Peter Nov 11 '19 at 04:33
  • 4
    @Peter `const` does imply `static` (i.e. internal linkage). But only in namespace scope. And exceptions apply. – eerorika Nov 11 '19 at 04:39

1 Answers1

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.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
  • when you say namespace scope are you referring to global scope? – csguy Nov 11 '19 at 05:10
  • im pretty sure you arent but the examples provided https://stackoverflow.com/questions/45987571/difference-between-constexpr-and-static-constexpr-global-variable are all in global scope i think? – csguy Nov 11 '19 at 05:24
  • ohhhh i get it now global scope is a kind of namespace scope – csguy Nov 11 '19 at 05:34