Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable-length arrays in C89?

Tags:

arrays

c

gcc

c99

c89

I've read that C89 does not support variable-length arrays, but the following experiment seems to disprove that:

#include <stdio.h>

int main()
{
   int x;
   printf("Enter a number: ");
   scanf("%d", &x);
   int a[x];
   a[0] = 1;
   // ...
   return 0;
}

When I compile as such (assuming filename is va_test.c):

gcc va_test.c -std=c89 -o va_test

It works...

What am I missing? :-)

like image 804
jasonbogd Avatar asked Nov 11 '10 22:11

jasonbogd


3 Answers

GCC always supported variable length arrays AFAIK. Setting -std to C89 doesn't turn off GCC extensions ...

Edit: In fact if you check here:

http://gcc.gnu.org/onlinedocs/gcc/C-Dialect-Options.html#C-Dialect-Options

Under -std= you will find the following:

ISO C90 programs (certain GNU extensions that conflict with ISO C90 are disabled). Same as -ansi for C code.

Pay close attention to the word "certain".

like image 106
Goz Avatar answered Sep 20 '22 13:09

Goz


C89 does not recognize // comments.

C89 does not allow definitions intermixed with code.

You need to fflush(stdout) after the printf to be sure of seing the prompt before the scanf.

main "looks better" as int main(void)

Try gcc -std=c89 -pedantic ... instead

like image 30
pmg Avatar answered Sep 23 '22 13:09

pmg


You're missing that without -pedantic, gcc isn't (and doesn't claim to be) a standard-conforming C compiler. Instead, it compiles a GNU dialect of C, which includes various extensions.

like image 20
Steve Jessop Avatar answered Sep 24 '22 13:09

Steve Jessop