2

In C++17, is there any difference between declaring a global constant like this:

namespace ns
{
static constexpr const auto global_variable = 47;
}

Specifying the const modifier as well, and:

namespace ns
{
static constexpr auto global_variable = 47;
}

Without specifying const? If yes, which are the differences and which version of the declaration is recommended in which scenarios?

nyarlathotep108
  • 5,275
  • 2
  • 26
  • 64
  • 1
    In C++17 you may as well define a global constant `inline` rather than `static`. Or just in an anonymous namespace. – DeiDei Dec 12 '19 at 15:24
  • 1
    In the examples given, no. But `static constexpr char* global_variable = "Happy";` applies the `constexpr` to the _type_ `char*`, which is as-if it was `char* const`. And that's not what you really want. So there you need to do `static constexpr char const* global_variable = "Happy";`. – Eljay Dec 12 '19 at 15:29
  • @DeiDei well it is already in a `namspace`, what are the benefits of making it `inline` instead of `static` in my example case? – nyarlathotep108 Dec 12 '19 at 15:36

2 Answers2

7

There is no difference, the constexpr specifier on a variable of object type implies const [dcl.constexpr]/9:

A constexpr specifier used in an object declaration declares the object as const. […]

Note that the static is redundant here as well because the const-qualified type already implies internal linkage [basic.link]/3.2:

A name having namespace scope has internal linkage if it is the name of

  • […]
  • non-inline variable of non-volatile const-qualified type that is neither explicitly declared extern nor previously declared to have external linkage […]
  • […]
Michael Kenzel
  • 15,508
  • 2
  • 30
  • 39
0

You don't need to have const here, constexpr implies const.

Oblivion
  • 7,176
  • 2
  • 14
  • 33