-1

I am compiling my C code using the gcc compiler

My code is

main()
{
    int i;
    scanf("%d",&i);
    int a[i];
}

... and it executes it without any warning. However, if I use:

main()
{
    int i;
    scanf("%d",&i);
    static int a[i];
}

... I get an error message saying the size of array is not constant.

If execution of program starts at main function it should not give such error. and if static data is allocated first before start of main(), how is the compiler able to generate such errors during during compile time?

Matt
  • 74,352
  • 26
  • 153
  • 180
shiv garg
  • 761
  • 1
  • 8
  • 26

1 Answers1

1

Variables length arrays are not allowed to be static from the draft C99 standard section 6.7.5.2 Array declarators paragraph 2 says (emphasis mine):

An ordinary identifier (as defined in 6.2.3) that has a variably modified type shall have either block scope and no linkage or function prototype scope. If an identifier is declared to be an object with static storage duration, it shall not have a variable length array type.

In C++ variable length arrays are not part of the standard and are a compiler extension but gcc should be be following the C99 rules there as well.

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740