Hi all,

I have a question about the constexpr variable specifications and how the 
compiler handles them. The constexpr specifier declares that it is possible to 
evaluate the value of the function or variable “at compile time”. If we look at 
the bellow simplified example:

int func(){
        int sum = 0;
        for (int i = 0; i < 3; i++){
                constexpr int j = i;
                sum +=j;
        }
        return sum;
}

The compiler will throw an error as:

“The value of ‘i' is not usable in a constant expression.”
However the value of ‘i’ is known during the compile time, and if I unroll this 
computation myself it works perfect, so why the compiler is not able to do that?
The main reason I am asking this is because I want to call a constexpr function 
for a few iteration which is known at compile time (instead of that “sum” in 
the for loop) , but using the iteration number in the call is prohibited, even 
though the number of iterations and iteration number  is known during the 
compile time to do the sum. When unrolling it by hand works, why the compiler 
refuses to handle this situation?

[I used gcc 9.3 with -O3 flag]

Thanks in advance,

Reply via email to