xmllmx
xmllmx

Reputation: 42379

Is it legal in C++17 to declare an array of size 0?

int main()
{
    int n[0];   
}

The code above is ok with Clang 4.0.

However, http://en.cppreference.com/w/cpp/language/array says:

The size of an array must be a value greater than zero.

Is it legal to declare an array of size 0 as per the C++17 standard?

Upvotes: 2

Views: 519

Answers (2)

NathanOliver
NathanOliver

Reputation: 180935

Is it legal to declare an array of size 0 as per the C++17 standard?

No, nothing has changed in C++17 to allow zero sized arrays. Per the C++17 draft [dcl.array]/1

In a declaration T D where D has the form

D1 [ constant-expressionopt] attribute-specifier-seqopt

[...]If the constant-expression is present, it shall be a converted constant expression of type std​::​size_­t and its value shall be greater than zero.[...]

emphasis mine

What you are seeing here is a non standard compiler extension that is allowing you to compile the code.

You can disable these extensions by using the -pedantic compiler flag.

Upvotes: 11

Andria
Andria

Reputation: 5085

It's "legal" only because it's an extension of gcc and clang. If you compile with -pedantic then you'll see that what you're doing is not working with the ISO C++ Standard

Upvotes: 3

Related Questions