How to convert int to const int to assign array size on stack?

前端 未结 2 1305
没有蜡笔的小新
没有蜡笔的小新 2021-02-13 10:01

I am trying to allocate a fixed size on stack to an integer array

#include
using namespace std;

int main(){

    int n1 = 10;
          


        
相关标签:
2条回答
  • 2021-02-13 10:16

    How should I typecast n1 to treat it as a const int?

    You cannot, not for this purpose.

    The size of the array must be what is called an Integral Constant Expression (ICE). The value must be computable at compile-time. A const int (or other const-qualified integer-type object) can be used in an Integral Constant Expression only if it is itself initialized with an Integral Constant Expression.

    A non-const object (like n1) cannot appear anywhere in an Integral Constant Expression.

    Have you considered using std::vector<int>?

    [Note--The cast is entirely unnecessary. Both of the following are both exactly the same:

    const int N = n1;
    const int N = const_cast<const int&>(n1);
    

    --End Note]

    0 讨论(0)
  • 2021-02-13 10:18

    Only fixed-size arrays can be allocated that way. Either allocate memory dynamically (int* foo = new int[N];) and delete it when you're done, or (preferably) use std::vector<int> instead.

    (Edit: GCC accepts that as an extension, but it's not part of the C++ standard.)

    0 讨论(0)
提交回复
热议问题