How to convert int to const int to assign array si

2020-06-09 06:34发布

问题:

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