2

I find that in the declaration of an array, we cannot specify the size of it like this

int a[0];

I know, empty size array illegal in C++, but In my code, empty size array compiler allowed and give the output.

My code is here :

#include <iostream>
using namespace std;

int main()
{
        int a[0];

        a[0] = 10;
        a[1] = 20;

        cout<<a[0]<<endl;
        cout<<a[1]<<endl;

        return 0;
}

Output:

10
20

Online compiler link : http://code.geeksforgeeks.org/TteOmO

So, My question is, Why is int a[0] allowed GCC compiler?

msc
  • 33,420
  • 29
  • 119
  • 214
  • Doing `int a[0]; a[0] = 10; a[1] = 20;` will lead to FireWorks(UB). – sameerkn Sep 13 '16 at 06:37
  • 1
    OP knows it is wrong, question is why does the compiler not raise an error. Answer to which, I suppose, would be that it cannot do everything for you ;) – slawekwin Sep 13 '16 at 06:39
  • `error: ISO C++ forbids zero-size array 'a' [-Wpedantic]int a[0];` – Praveen Sep 13 '16 at 06:39
  • 1
    Most likely because adding a special rule disallowing it would be too much added parser complexity for very little gain. – user4581301 Sep 13 '16 at 06:39
  • 1
    It's allowed because it's a [gcc extension](https://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html#Zero-Length). – molbdnilo Sep 13 '16 at 06:45

2 Answers2

5

It issues a warning, for example clang outputs:

warning: zero size arrays are an extension [-Wzero-length-array]

this is undefined behaviour:

    a[0] = 10;
    a[1] = 20;

Zero length arrays are extensions for gcc, why - you can read on it here:

https://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html

They are very useful as the last element of a structure that is really a header for a variable-length object:

This is actually C extension but it looks like it also is used in C++, probably to make it easier to use existing structures from C that uses this extension.

marcinj
  • 48,511
  • 9
  • 79
  • 100
  • Also comment that the more portable solution for this type of structures is an array without size, like `a[]`. This is added in C99: http://stackoverflow.com/a/17185530/3742943 – LoPiTaL Sep 13 '16 at 06:48
0

Please Look Into This

What happens if I define a 0-size array in C/C++? If It's a good compiler it will catch that and give a warning. but with pedantic option compiler can catch it.

Community
  • 1
  • 1
Shankar Shastri
  • 1,134
  • 11
  • 18