wupiku
wupiku

Reputation: 85

Why can I compile with this illegal C statement without any error?

I came across this line in my studies:

It's illegal for an array initializer to be completely empty. So we have to put a single 0 inside the braces.

But when I compile and run a completely empty array with nothing inside only braces like int a[]= {}; it compiles and runs fine.

Upvotes: 1

Views: 128

Answers (1)

giusti
giusti

Reputation: 3538

Compilers can extend the language. Some use their extensions by default, but they usually allow you to specify a particular standard. In GCC you can do that with the -std=XXX argument. For instance, -std=c17 forces the compiler to adhere to the C 2017 standard.

However, there are some things in the standard that the compilers will ignore even if you issue a -std flag. It's the case with your particular example. Both GCC and clang will refuse to complain about empty initializers unless you have a -pedantic flag. I'll give an example.

Program:

int main(void)
{
    int arr[] = {};
    return arr[0];  // this would be invalid even if the above was ok
}

Compiling:

gcc t.c -std=c17 -pedantic
t.c: In function ‘main’:
t.c:3:14: warning: ISO C forbids empty initializer braces [-Wpedantic]
    3 |  int arr[] = {};
      |              ^
t.c:3:6: error: zero or negative size array ‘arr’
    3 |  int arr[] = {};
      |      ^~~

If you want the pedantic warnings to become errors, you can use -pedantic-errors instead.

Upvotes: 1

Related Questions