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

前端 未结 2 1304
没有蜡笔的小新
没有蜡笔的小新 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?

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

    const int N = n1;
    const int N = const_cast(n1);
    

    --End Note]

提交回复
热议问题