18

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.

0

2 Answers 2

23

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]

Sign up to request clarification or add additional context in comments.

3 Comments

Just to add one more detail: gcc compiles it as an extension -- in fact, it allows other expressions that aren't even as close to conforming, like int x(int a) { int b[a]; }
Ah, thank you, @JerryCoffin. I did not see the edit when I posted.
Instead of const int we could go for constexpr int, that way compiler will make sure that the value is ICE during assignment, instead of when you're trying to allocate an array.
4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.