MK.
MK.

Reputation: 4027

c++ syntax for initializing arrays

I came across this code fragment, it compiles fine with g++. I can understand what is happening, but is this valid c++ or an extension?

const char* msgs[] = 
{
    [0] = "message0",
    [1] = "message1"
};

Upvotes: 3

Views: 49

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310930

It is valid C syntax. In C you may use so-called designators.

designator:
    [ constant-expression ]
    . identifier

One more example

struct A
{
   int x;
   int y;
} a = { .x = 10, .y = 20 };

However it is not valid in C++. In C++ you should write

const char* msgs[] = 
{
    "message0",
    "message1"
};

If a C++ compiler compiles the declaration you showed then it is its own language extension that is not C++ compliant.

Upvotes: 2

Related Questions