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 fixederror 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.
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”.
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.
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.
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.
How should I typecast
n1
to treat it as aconst 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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With