I am trying to allocate a fixed size on stack to an integer array
#include
using namespace std;
int main(){
int n1 = 10;
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
?
[Note--The cast is entirely unnecessary. Both of the following are both exactly the same:
const int N = n1;
const int N = const_cast(n1);
--End Note]