Search code examples
c++arraysinitializationenumeration

C++ weirdness with array initialization from brace-enclosed lists


I can't get the code below to compile with either GCC or Clang. Tried both C++11 and C++14.

My question:
Is there any logical reason for this not to be implemented? Myself, I can't think of any... See below for my workaround.

enum class fruit {
    APPLES,
    ORANGES,
    STRAWBERRIES
};
struct Area {float x, y, width, height;};
const Area test[] = {
    [fruit::APPLES] = {1,2,3,4},
    [fruit::ORANGES] = {2,2,3,4},
    [fruit::STRAWBERRIES] = {3,2,3,4}
};

This though will compile just fine:

namespace fruit { // instead of enum class, this works
    enum {
            APPLES,
            ORANGES,
            STRAWBERRIES
    };
}
struct Area {float x, y, width, height;};
const Area test[] = {
    [fruit::APPLES] = {1,2,3,4},
    [fruit::ORANGES] = {2,2,3,4},
    [fruit::STRAWBERRIES] = {3,2,3,4}
};

Solution

  • Okay, so I will answer this myself from what I learned in the comments.

    This is apparently called using "designated initializer" and it's a C99 feature, not a part of the C++ standard (even if it compiles in some cases):

    int array[] = {
        [1] = 11,
        [0] = 22
    };
    

    The code in my question compiles for me if I make these changes though:

    [fruit::APPLES] = {1,2,3,4}
    

    Change into:

    [(int)fruit::APPLES] = {1,2,3,4}
    

    Or into (the more correct way):

    [static_cast<int>(fruit::APPLES)] = {1,2,3,4}
    

    But if you want to be standard compatible it's best not to use designated initializers and instead rewrite the code...