c++ - How to convert int to const int to assign array size on stack? -


i trying allocate fixed size on stack 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, gives error on last line using n define fixed
error c2057: expected constant expression.

however, if define n const int n = 10, code compiles fine. how should typecast n1 trat const int?

i tried : const int n = const_cast<const int>(n1) gives error.

edit : using ms vc++ 2008 compile this... g++ compiles fine.

how should typecast n1 treat const int?

you cannot, not purpose.

the size of array must called integral constant expression (ice). value must computable @ compile-time. const int (or other const-qualified integer-type object) can used in integral constant expression if initialized integral constant expression.

a non-const object (like n1) cannot appear anywhere in integral constant expression.

have considered using std::vector<int>?

[note--the cast entirely unnecessary. both of following both same:

const int n = n1; const int n = const_cast<const int&>(n1); 

--end note]


Comments

Popular posts from this blog

jasper reports - Fixed header in Excel using JasperReports -

media player - Android: mediaplayer went away with unhandled events -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -