Accepting Variable Length Arrays (VLAs) in C Despite Non-Standard Status
Although C doesn't officially support Variable Length Arrays (VLAs), both g and clang compilers surprisingly accept them as valid syntax. This raises questions about the compiler's behavior and the standard's position on VLAs.
Compiler Acceptance
C compilers like g and clang allow VLAs as a non-standard extension. This is likely due to historical compatibility with older C compilers that allowed such declarations.
Standard Definition
The C standard prohibits VLAs as per the grammar rule in [dcl.array]. Only constant expressions are permitted for specifying array sizes. In the example code provided, n is not a constant expression, making the VLA declaration invalid according to the standard.
Implementation Details
Despite being non-standard, VLAs in C are often implemented by allocating memory on the stack and using a loop to access elements. However, this behavior is compiler-dependent and may vary across different implementations.
Implications
Recommendation
For code portability and to ensure compliance with the C standard, it is recommended to use dynamic memory allocation (e.g., new[]) for creating arrays whose sizes are not known at compile time.
The above is the detailed content of Why Do g and clang Accept Variable Length Arrays (VLAs) in C Despite the Standard Prohibiting Them?. For more information, please follow other related articles on the PHP Chinese website!