Variable-Sized Arrays in C : Compiling with GCC Extensions
C typically requires array sizes to be constant integers. However, GCC provides an extension that allows for the use of non-constant variables to declare array sizes.
Question:
Why does the following code compile successfully with GCC?
<code class="cpp">void f(int i) { int v1[i]; } int main() { int i = 3; int v2[i]; f(5); }</code>
Answer:
This behavior is an extension to the C standard introduced by GCC. By default, GCC allows you to use non-constant variables to specify array sizes.
However, there are important caveats to note:
Using the Extension:
To utilize this extension, simply declare your array with a non-constant variable as its size:
<code class="cpp">int arraySize = 5; int myArray[arraySize];</code>
Overcoming Portability Concerns:
If portability is a concern, you can use the std::vector container instead of arrays with variable sizes:
<code class="cpp">std::vector<int> myVector(arraySize);</code>
By utilizing this extension, you gain greater flexibility in managing array sizes in dynamic situations. However, it's important to be aware of its limitations and consider its portability implications when using it in your projects.
The above is the detailed content of Why does GCC allow variable-sized arrays in C ?. For more information, please follow other related articles on the PHP Chinese website!