Home > Backend Development > C++ > Is `int size = 10;` a Constant Expression in C : A Compiler Compatibility Issue?

Is `int size = 10;` a Constant Expression in C : A Compiler Compatibility Issue?

Patricia Arquette
Release: 2024-12-09 22:08:15
Original
878 people have browsed it

Is `int size = 10;` a Constant Expression in C  : A Compiler Compatibility Issue?

Does "int size = 10;" Yield a Constant Expression?

The code snippet below compiles successfully in gcc 4.8 and Clang 3.2:

int main()
{
  int size = 10;
  int arr[size];
}
Copy after login

According to the C Standard (8.3.4/1), the size of an array must be an integral constant expression. However, it appears that "size" in the code is not an integral constant expression. Is this a compiler bug or an oversight in our understanding?

Visual Studio C rejects this code with the message: "error C2466: cannot allocate an array of constant size 0". This implies that the compiler considers "size" to be zero.

Explanation

gcc and Clang support variable length arrays (VLA) as an extension in C . VLA is a C99 feature that allows the size of an array to be determined at runtime. In the code snippet, "size" is determined at compile-time, but it is not a literal constant. Therefore, "size" is considered a VLA in gcc and Clang.

Visual Studio, on the other hand, does not support VLA and adheres to the C Standard. As a result, it rejects the code because "size" is not a literal constant.

Standard Compliance

The C Standard defines an integral constant expression as an expression that, when evaluated, results in a prvalue of integral or unscoped enumeration type. In this case, "size" is initialized with a literal value (10), which makes it an integral constant expression.

Using the "-pedantic" flag in gcc and Clang will generate a warning about variable length arrays in the code snippet. Using "-pedantic-errors" will make the warning an error.

Solution

To comply with the C Standard, "size" can be declared as a const or constexpr integer:

const int size = 10;
Copy after login

or

constexpr int size = 10;
Copy after login

The above is the detailed content of Is `int size = 10;` a Constant Expression in C : A Compiler Compatibility Issue?. 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