Array Size Declaration with Non-Constant Variables
Contrary to the widely accepted notion that array sizes in C must be constant integers, recent observations have revealed that some compilers allow for greater flexibility in this regard. While the C standard dictates that array bounds must be constant expressions, GCC introduced an extension that enables the use of non-constant variables in array size declarations.
Consider the following example:
<code class="c++">int ArraySize = 5; int MyArray[ArraySize];</code>
In standard C , this code would generate a compiler error because ArraySize is not a constant. However, GCC happily compiles it without any issues.
To understand this behavior, it is essential to acknowledge that GCC's extension is a deviation from the C standard. The excerpt from "The C Programming Language" by Bjarne Stroustrup explicitly states that array bounds must be constant expressions.
Despite this, GCC's extension provides a convenient way to dynamically allocate arrays at runtime. One could argue that this flexibility comes at the cost of portability, as code that relies on GCC's extension may not compile on other compliant C compilers.
If portability is a concern, GCC offers options to enforce standard compliance. Passing the -pedantic flag during compilation results in a warning for non-constant array size declarations, and -std=c 98 treats it as an error. These options prioritize strict adherence to the C standard over runtime convenience.
The above is the detailed content of Can You Use Non-Constant Variables to Declare Array Sizes in C ?. For more information, please follow other related articles on the PHP Chinese website!