lpetru
lpetru

Reputation: 117

Why is array initialization with brackets () marked as error by compilers?

I was researching the initializer syntax in C++, and according to cppreference, there are three possible ways of writing it, 1) brackets, 2) equal sign, 3) braces.

When trying to initialize an array with the 1) brackets syntax, I encounter an error.

int test() {
    int a[](1);

    return 0;
}

Testing that on Compiler Explorer, I get from clang 11.0.0

error: array initializer must be an initializer list
        int a[](1);
            ^

And similarly, on the same site with gcc 10.2

error: array must be initialized with a brace-enclosed initializer

Now, I know how to use braces to initialize the array without an error. But that is not the point of this question.

I'm looking for a correspondence of C++ standard with this reported error.

I'm looking at this standard draft timsong-cpp (should be around the C++ 20 time). The section "(17.1) If the initializer is a (non-parenthesized) braced-init-list or is = braced-init-list, ..." talks about braced lists - not our case.

Then there is a section "(17.5) Otherwise, if the destination type is an array, the object is initialized as follows ..."

I think this should cover our case. It is about initialization of an array, it is also an "otherwise" section, meaning it does nat talk about the braced lists. It could talk about 1) brackets or 2) equal sign, but from further text we see that it requires an expression-list:

"Let x1, …, xk be the elements of the expression-list. "

That expression list will be there when using the 1) brackets syntax. As a side note, the section "14 If the entity being initialized ..." requires the expression list to only be a single expression in this case.

According to the standard wording, the declaration int a[](1); should set the length of the array to 1 and initialize its only element with value 1. But that does not happen in the implementations.

Which other parts of the standard can prevent this interpretation? Or is there something else I'm missing?

Upvotes: 3

Views: 487

Answers (1)

cigien
cigien

Reputation: 60208

The feature that you're trying to use was added in C++20, and is called "Parenthesized initialization of aggregates". As can be seen from the compiler support page, GCC supports this from GCC10, whereas Clang doesn't support this feature yet.

Upvotes: 7

Related Questions