Home > Backend Development > C++ > body text

Can You Declare an Array with a Variable Size in C ?

DDD
Release: 2024-11-01 22:11:29
Original
387 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!