c++ - Declaring arrays with const variables -
i trying create multidimensional array, when pass const int value can't compile. error "expression must have constant value" each dimension.
class matrix { public: matrix(int rowcount, int columncount, int scalarinput) { const int row_c = rowcount; const int colum_c = columncount; const int scalar_c = scalarinput; matrixcalculation(row_c, colum_c, scalar_c); } void matrixcalculation(const int i, const int j, const int s) { int matrixarray[i][j]; // error here, , j: "expression must have constant value" } }; thanks
array dimensions must compile-time constant, , const doesn't mean that.
a const object cannot change value after initialisation, initialiser may determined @ runtime (e.g. const int x = rand()) so, in general, these objects not valid candidates array dimensions.
introducing... constexpr.
if plonk keyword constexpr in front of dimensions, off start. compiler prevent breaking contract of constexpr, , consequently enable use shiny new constexpr object array dimension.
alas, in example, are breaking contract already, since inputs non-constant. tough cookies.
use vector instead.
Comments
Post a Comment