0

I usually use enums to keep two arrays consistent by defining them like following:

enum foo {
    ZERO = 0,
    ONE,
    TWO,
};

int int_array[] = {
    [ZERO] = 0,
    [ONE] = 1,
    [TWO] = 2
};

char *str_array[] = {
    [ZERO] = "ZERO",
    [ONE] = "ONE",
    [TWO] = "TWO"
};

This code compiles fine for c, but throws following error when used in a cpp module.

expected primary-expression before ‘[’ token

Error is for each line in both array declarations. What's the problem here?

too honest for this site
  • 12,050
  • 4
  • 30
  • 52
ronakg
  • 4,038
  • 21
  • 46

2 Answers2

1

It's not valid syntax for C++. You can initialize arrays in following way:

int int_array[] = { 0, 1, 2 };

char *str_array[] = {
    "ZERO",
    "ONE",
    "TWO"
};
CodeFuller
  • 30,317
  • 3
  • 63
  • 79
1

The C++ does not support the so-called designator. Initialization that is allowed in C.

So the compiler issues a message.

In C++ you have to write just the following way

int int_array[] = { 0, 1, 2 };

const char *str_array[] = { "ZERO", "ONE", "TWO" }; 
^^^^^^
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Isn't it a GCC extension? Or is it standard in C99 and above? I'm talking about C, BTW. – Spikatrix Apr 05 '16 at 04:20
  • @CoolGuy The designator initialization was introduced in the C99. Maybe GCC also has its own language extension. I do not know. – Vlad from Moscow Apr 05 '16 at 04:22
  • @CoolGuy: gcc introduced this as an extension before C99 was released for `struct` members and arrays. It was added to the standard with a slightly different syntax with C99. Not added to the standard was to specify a range of indexes. See https://gcc.gnu.org/onlinedocs/gcc-4.9.3/gcc/Designated-Inits.html#Designated-Inits – too honest for this site Apr 05 '16 at 13:14