Reputation: 978
Here's a C program one of my friends had written.
From what I know, arrays had to be initialised at compile time before C99 introduced VLA's, or using malloc
during runtime.
But here the program accepts value of a const
from the user and initialises the array accordingly.
It's working fine, even with gcc -std=c89
, but looks very wrong to me.
Is it all compiler dependent?
#include <stdio.h>
int
main()
{
int const n;
scanf("%d", &n);
printf("n is %d\n", n);
int arr[n];
int i;
for(i = 0; i < n; i++)
arr[i] = i;
for(i = 0; i < n; i++)
printf("%d, ", arr[i]);
return 0;
}
Upvotes: 2
Views: 1412
Reputation: 106122
This called Variable Length Arrays and allowed in C99 . Compiling in c89
mode with -pedantic
flag, compiler will give you warnings
[Warning] writing into constant object (argument 2) [-Wformat]
[Warning] ISO C90 forbids variable length array 'arr' [-Wvla]
[Warning] ISO C90 forbids mixed declarations and code [-pedantic]
Upvotes: 1
Reputation: 145919
Add -pedantic
to your compile options (e.g, -Wall -std=c89 -pedantic
) and gcc
will tell you:
warning: ISO C90 forbids variable length array ‘arr’
which means that your program is indeed not c89/c90 compliant.
Change with -pedantic
with -pedantic-errors
and gcc
will stop translation.
Upvotes: 2