Home > Backend Development > C++ > Can You Use Non-Constant Variables to Declare Array Sizes in C ?

Can You Use Non-Constant Variables to Declare Array Sizes in C ?

Linda Hamilton
Release: 2024-11-02 11:56:31
Original
954 people have browsed it

Can You Use Non-Constant Variables to Declare Array Sizes in C  ?

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template