简体   繁体   中英

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?

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

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’

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

Compilers are permitted to have modes other than strict conformance to the C standard.

In effect, the C standard is just one specification. There is no law saying you must conform to it and no law saying a compiler developer must conform to it.

So a compiler is permitted to define its own variations on a language and to compile using its own specification or even a specification written by some third party.

More than that, the C standard defines the language to be extensible. There are many behaviors that an implementation is permitted to define while remaining conforming with the C standard. The C standard even specifies that a conforming program is any program acceptable to a conforming implementation. This means that a program that uses a compiler extension is still a conforming C program (in the absence of any other issues). (However, it is not a strictly conforming program; those are programs that do not use extensions.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM