Home > Backend Development > C++ > body text

\'Why Does Declaring an Array with a Runtime-Determined Size Cause an \'Expected Constant Expression\' Error?\'

Linda Hamilton
Release: 2024-10-25 04:10:29
Original
386 people have browsed it

Error: "Expected Constant Expression" for Array Size

When attempting to declare an array with a runtime-determined size, as in the following code snippet:

<code class="cpp">int size = 100;
float x[size][2];</code>
Copy after login

you may encounter the error "expected constant expression." This error occurs because declared arrays must have their size determined at compile time.

Solution: Use a Vector or Dynamic Array Allocation

To resolve this issue, consider using a vector or dynamic array allocation. Using a vector, you can specify the size at runtime:

<code class="cpp">std::vector< std::array<float, 2> > x(size);</code>
Copy after login

Alternatively, you can use the new operator to dynamically allocate the array:

<code class="cpp">float (*px)[2] = new float[size][2];</code>
Copy after login

Other Options:

  • Boost Array: If you do not have C 11, use Boost library's boost::array.
  • Custom Array Type: Create a custom array type that can be placed in a vector.
  • Identity Template: Simplify syntax for dynamic array allocation using an identity template.
  • Vector of Pairs: Use a vector of std::pair to store the data.

The above is the detailed content of \'Why Does Declaring an Array with a Runtime-Determined Size Cause an \'Expected Constant Expression\' Error?\'. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!