0

When declaring a static constant array in my class like that

static const int myArray[] = {1, 2, 3, 999};

I get an error like "In-class initializer for static data member of type const int[] requires constexpr specifier". When I make it this way and declare it as

static constexpr int myArray[] = {1, 2, 3, 999};

it works. Why is it not possible to declare static constant arrays? What am I missing?

1
  • 4
    It is possible to declare static constant arrays. It's just not possible to specify an initializer for them inline. Commented May 5, 2014 at 18:17

1 Answer 1

2

It seems that there is a bit of confusion about declaration and definition / initialization in the question.

Before C++11, the definition (which often includes the initialization) of a static member should be done out-of-class, with the exception of static constants of integral or enumeration types. From Stroustrup's C++ FAQ:

to use in-class initialization syntax, the constant must be a static const of integral or enumeration type initialized by a constant expression

Even in this case, if the definition is required (e.g when taking the address of the static member), it should be defined out-of-class.

C++11 introduces the constexpr specifier to signal compile time initialization, and allows static members to be initialized in-class if declared constexpr (check Constant static members section in the reference of static). It also allows in-class initialization of non-static members but with a wider meaning.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.