Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are variable-length arrays really not allowed in C90?

I'm reading about VLAs in C Primer Plus, and this book strictly says that the introduction of VLAs to C began with the C99 standard. Whenever I attempt to declare a loop control variable within the header of a for loop, gcc informs me that this action only allowed in C99 mode. However, the following test code compiles and works (although it prints garbage variables, which is to be expected considering none of the array elements were initialized).

#include <stdio.h>

int main(){
    int x; 
    int i = 9; 
    int array[i]; 

    for(x = 0; x < i; x++)
        printf("%d\n", array[x]);

    return 0; 
}

If I'm not in C99 mode, how could this possibly be legal?

like image 602
Theo Chronic Avatar asked Jul 15 '13 12:07

Theo Chronic


2 Answers

The book is correct, variable length arrays have been supported since C99 and if you build with the following options:

gcc -std=c89 -pedantic

you will receive an warning:

warning: ISO C90 forbids variable length array ‘array’ [-Wvla]

If you want this to be an error you can use -pedantic-errors. gcc supported this as an extension before c99, you can build explicitly in c99 mode and you will see no errors:

gcc -std=c99 -pedantic

The Language Standards Supported by GCC pages goes into details about which standard gcc supports for C and it states that:

By default, GCC provides some extensions to the C language that on rare occasions conflict with the C standard

like image 187
Shafik Yaghmour Avatar answered Sep 28 '22 01:09

Shafik Yaghmour


If I'm not in C99 mode, how could this possibly be legal?

It’s not. However, GCC allows it as a compiler extension.

You can force GCC to be strict about this by passing the -pedantic flag:

$ gcc -std=c89 -pedantic main.c
main.c: In function ‘main’:
main.c:6: warning: ISO C90 forbids variable-size array ‘array’
like image 44
Konrad Rudolph Avatar answered Sep 28 '22 03:09

Konrad Rudolph