Home > Article > Backend Development > Can You Declare an Array with a Variable Size in C ?
Variable Array Size Declaration in C
In C , the size of an array is typically expected to be a constant integer value. However, the question arises whether it's possible to declare an array with a non-constant variable as its size.
As highlighted by Bjarne Stroustrup in The C Programming Language, "array bound, must be a constant expression." As a result, the code below is considered incorrect:
<code class="cpp">int ArraySize = 5; int MyArray[ArraySize]; // incorrect</code>
However, surprisingly, on some systems like GCC v4.4.0, the code compiles successfully:
<code class="cpp">void f(int i) { int v2[i]; } int main() { int i = 3; int v1[i]; f(5); }</code>
This unexpected behavior is due to a GCC extension to the standard. By default, GCC allows the usage of a non-constant variable as an array size. However, this may not be a feature supported across all compilers or platforms.
If portability is a requirement, it's highly recommended to use the -pedantic option with GCC to enable warnings for this extension or use -std=c 98 to raise an error. By adhering to the standard, code will be more reliable and cross-platform compatible.
The above is the detailed content of Can You Declare an Array with a Variable Size in C ?. For more information, please follow other related articles on the PHP Chinese website!