Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 873
memC Avatar asked Mar 07 '12 06:03

memC


People also ask

How do you convert a variable to a constant in C++?

Approach used in the below program as follows − Then create a third pointer, let us say “c” of data type int to be used for const_cast. Now pass our constant pointer “b” into const_cast and keep it equal to our pointer “c”. Finally make changes in the value of our pointer “c”.

What is the size of const variable?

An int type has a range of (at least) -32768 to 32767 but constants have to start with a digit so integer constants only have a range of 0-32767 on a 16-bit platform.

What is const int * const?

const int* const is a constant pointer to constant integer This means that the variable being declared is a constant pointer pointing to a constant integer. Effectively, this implies that a constant pointer is pointing to a constant value.

How do you use const int?

Simple Use of 'const'One has to initialise it immediately in the constructor because, of course, one cannot set the value later as that would be altering it. For example, const int Constant1=96; will create an integer constant, unimaginatively called ' Constant1 ', with the value 96.


1 Answers

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]

like image 121
James McNellis Avatar answered Oct 29 '22 03:10

James McNellis