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

假装没事ソ 提交于 2019-12-04 17:45:49

问题


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

#include<iostream>
using namespace std;

int main(){

    int n1 = 10;
    const int N = const_cast<const int&>(n1);
    //const int N = 10;
    cout<<" N="<<N<<endl;
    int foo[N];
    return 0;
}

However, this gives an error on the last line where I am using N to define a fixed
error C2057: expected constant expression.

However, if I define N as const int N = 10, the code compiles just fine. How should I typecast n1 to trat it as a const int?

I tried : const int N = const_cast<const int>(n1) but that gives error.

EDIT : I am using MS VC++ 2008 to compile this... with g++ it compiles fine.


回答1:


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]




回答2:


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.)



来源:https://stackoverflow.com/questions/9596650/how-to-convert-int-to-const-int-to-assign-array-size-on-stack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!