3

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?

3
  • 1
    In C++17 you may as well define a global constant inline rather than static. Or just in an anonymous namespace. Commented Dec 12, 2019 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";. Commented Dec 12, 2019 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? Commented Dec 12, 2019 at 15:36

2 Answers 2

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 […]
  • […]
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.