2
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?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
xmllmx
  • 39,765
  • 26
  • 162
  • 323
  • 2
    see [What is the use of 0-length array (or std::array)?](http://stackoverflow.com/q/26209190/1708801) – Shafik Yaghmour Apr 13 '17 at 16:22
  • 7
    [More warnings.](https://wandbox.org/permlink/EgXzQkeKoGQhdvVK) When it comes to whether something is standard or an extension, `-pedantic` is the appropriate flag. – chris Apr 13 '17 at 16:23

2 Answers2

11

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.

Community
  • 1
  • 1
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
3

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

Andria
  • 4,712
  • 2
  • 22
  • 38