Why this code doesn’t compile
#include <stdio.h>
int x=5;
int a[x];
int main()
{
a[0]=5;
printf("%d\n",a[0]);
return 0;
}
When compiled with gcc filename.c -Wall -ansi -pedantic it produces a error
error: variably modified ‘a’ at file scope
However this code compiles although giving warnings but gives correct output:
#include <stdio.h>
int main()
{
int x=5;
int a[x];
a[0]=5;
printf("%d\n",a[0]);
return 0;
}
warning: ISO C90 forbids variable length array ‘a’ [-Wvla]
However if i try to compile this using g++ filename.c -Wall -ansi -pedantic it produces no warnings and gives correct output too
#include <stdio.h>
const int x=5;
int a[x];
int main()
{
a[0]=5;
printf("%d\n",a[0]);
return 0;
}
I am using gcc version 4.7.0
Please explain in detail what’s happening ?
In C(unlike C++) const declarations do not produce constant expressions, i.e. in C you can’t use a const int object as array size in a non-VLA array declaration.
So,
is valid in C++ but invalid in C. Equivalent C code will be:
Note that:
const in c doesn’t mean constant. It means “read only”.
Note variable length arrays became a part of the C standard only in C99 prior to that the standard did not allow them though most compilers allowed them as a extension.
The first code snippet doesn’t compile because the array subscript needs be a constant which it is not. Also, variable length arrays cannot be declared at global scope.
The second code snippet doesn’t compile because variable length arrays were not part of standard prior to c99.
The third snippet compiles because const declarations produce constant expressions in C++ unlike C.