The how
variable is indeed const, but is not a constant expression. Such constant expressions are values and functions that have a known value and result at compile time, something known by the compiler before the program runs.
You can annotate your code to tell the compiler which variable should have a known value at compile time. This is what the constexpr
keyword is for.
However, the pow
function is not marked as constexpr
so it's only useable at runtime and not also at compile time. You must implement your own function there:
constexpr auto power(int value, int exponent) -> int {
for (int i = 0 ; i < exponent ; i++) {
value *= value;
}
return value;
}
constexpr int inputs = 1, layers = 2, layerN = 3, output = 1;
constexpr int how = inputs * layerN + power(layerN,layers) + output * layerN;
Then it will be useable in a array size:
float w[how];
Live example
Also note that with this power function we created, we can revert back to const
and the compiler will still accept it:
const int how = inputs * layerN + power(layerN, layers) + output * layerN;
float w[how];
The difference is that constexpr
enforce compile time knowability, and const does not and you get the error later.