Steve Van Opstal
Steve Van Opstal

Reputation: 1111

Why does array size initialization differ inside or outside a class/struct/...?

The first example will automagically know it's size by the elements it is initialized with. The second example requires you to explicitly define the length of the array (to get it working). Why is this the case? Is there a reason behind this?

Array initialization outside a class/struct/...

const int intArray[] = { 0, 1, 2 };

struct Example
{
    int SizeOfArray()
    {
        return sizeof(intArray);
    }
};

Array initialization inside a class/struct/...

Faulting

struct Example
{
    const int intArray[] = { 0, 1, 2 };

    int SizeOfArray()
    {
        return sizeof(intArray);
    }
};

Error: cannot specify explicit initializer for arrays

Solution

struct Example
{
    const int intArray[3] = { 0, 1, 2 };

    int SizeOfArray()
    {
        return sizeof(intArray);
    }
};

Upvotes: 1

Views: 175

Answers (1)

xaizek
xaizek

Reputation: 5252

I think it's because in-class/struct initialization is just syntactic sugar for writing part of initializer list in a different place. According to this, your faulting example is equal to the following:

struct Example
{
    const int intArray[];

    Example() :
       // start of compiler-generated pseudo code
       intArray[0](0),
       intArray[1](1),
       intArray[2](2)
       // end of compiler-generated pseudo code
    {
    }

    int SizeOfArray()
    {
       return sizeof(intArray);
    }
};

The code above obviously defines an incomplete structure of unknown size, just as @harper said in his comment.

P.S. Couldn't find proof in the standard, but I'm pretty sure that it covers this case, probably implicitly.

Upvotes: 3

Related Questions