Home > Backend Development > C++ > Is `int size = 10;` a Valid Constant Expression for Array Sizing in C ?

Is `int size = 10;` a Valid Constant Expression for Array Sizing in C ?

Linda Hamilton
Release: 2024-12-09 21:15:10
Original
500 people have browsed it

Is `int size = 10;` a Valid Constant Expression for Array Sizing in C  ?

Is "int size = 10;" a Constant Expression?

The code snippet:

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

raises questions about whether the variable length array (VLA) is a valid C feature.

The Standard's Perspective

The C Standard (8.3.4/1) mandates that array sizes be integral constant expressions, which "size" appears not to be. Compilers like GCC and Clang accept this code due to their support for VLAs as an extension in C . Visual Studio, adhering to the standard, rejects it.

Variable Length Arrays

VLAs are a C99 feature that allows arrays with dynamically determined sizes. GCC and Clang extend this functionality to C . However, VLAs are not part of the C standard and using the -pedantic flag in GCC/Clang will generate warnings or errors.

Integral Constant Expressions

According to the C draft standard (5.19/3), an integral constant expression is an expression of an integral or unscoped enumeration type, implicitly converted to a prvalue, that satisfies the criteria for a core constant expression.

Making "size" a Constant Expression

To adhere to the standard, "size" must be declared an integral constant expression. This can be achieved by:

  • Using const: const int size = 10;
  • Using constexpr: constexpr int size = 10;

Conclusion

GCC and Clang's acceptance of VLAs is an extension and not a standard feature in C . Visual Studio's rejection is in compliance with the standard. To use VLA-like functionality in standard C , it's recommended to use const or constexpr to make array sizes integral constant expressions.

The above is the detailed content of Is `int size = 10;` a Valid Constant Expression for Array Sizing 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