I'm playing a little bit with constexpr
recursion and try to see how it is compiled and I don't understand under which circumstances gcc
choose to calculate the recursion at compile time or at run time.
I'm using the following factorial calculation code :
#include <iostream>
constexpr unsigned int factorial(unsigned int i)
{
return i > 0 ? i*factorial(i-1) : 1;
}
int main(void)
{
std::cout << factorial(X) << std::endl;
}
and I change the value x
in the factorial.
- When compiling without optimization, the expression is not calculated at compile time.
- When compiling with the
-O1
flag, the expression is still not calculated at compile time. - With
-O2
, the expression is calculated at compile time ifx < 9
. After this value, the factorial is implemented inline as a loop. Changing the value of-fconstexpr-depth
flag doesn't change a thing. - With
-O3
, the expression is calculated at compile timeif x < 7
. After this value, the factorial is implemented inline with x86 xmm extension. - If I change the product for an sum in the factorial function, I obtain compile time calculation up to
10000
or more and reducing or increasing the value of-fconstexpr-depth
doesn't change anything.
Does anyone knows what are the rules for gcc 4.7 to implement the recursive function as compile-time or run-time?