Home > Article > Backend Development > Can GCC Compilers Use Variable-Sized Arrays in C ?
Variable-Sized Arrays: A GCC Extension
The C standard dictates that an array's size must be a constant integer when it is declared. However, the question raises the surprising observation that a code snippet using a non-constant variable for the array size compiles successfully in GCC.
The GCC Extension
GCC introduces an extension to the standard, allowing the use of non-constant variables for array sizes. As mentioned in the quoted section from "The C Programming Language", this is not supported by the standard.
The Surprise
The code snippet in the question declares an array v1 and a function f that takes an integer argument (representing the array size). When assigning a value to v2 in f, GCC allows this non-standard behavior.
Implications
Although GCC permits this extension, it is important to note that it is not part of the C standard. Using it may lead to portability issues with other compilers or systems that do not support the extension.
Enforcement and Warnings
Compilers can enforce the standard through options like -pedantic. Using this option, GCC will issue a warning when encountering non-standard constructions like variable-sized arrays. Similarly, specifying -std=c 98 makes this construct an error.
Conclusion
GCC's extension allows for the declaration of variable-sized arrays, but it is crucial to be aware that this is not part of the C standard. For portability and adherence to the standard, using constant array sizes is recommended.
The above is the detailed content of Can GCC Compilers Use Variable-Sized Arrays in C ?. For more information, please follow other related articles on the PHP Chinese website!