Search code examples
cgccvariable-length-array

Why doesn't work Variable length array as a globally?


If I write variable length array as a locally, like this:

#include <stdio.h>

int main()
{
    int i=1;
    int a[i];
    printf("%zu",sizeof(a));
}

It working fine in GCC compiler.

But, If I write Variable length array as a globally, like this:

#include <stdio.h>
int i=1;
int a[i];
int main()
{
    printf("%zu",sizeof(a));
}

Then, GCC compiler gives following an error:

prog.c:4:5: error: variably modified 'a' at file scope
  int a[i];

Solution

  • From standard 6.7.6.2

    If an identifier is declared to be an object with static or thread storage duration, it shall not have a variable length array type.