I am trying to understand how constexpr works. I am initializing a constexpr variable from the return value of a constexpr function as in the below code.
#include <iostream> using namespace std; constexpr size_t n = 40; constexpr size_t Fib(const size_t n) { if (n <= 1) return n; return Fib(n - 1) + Fib(n - 2); } int main() { //constexpr size_t Value = Fib(n); // ----> Line 1 const size_t Value = Fib(n); // ----> Line 2 cout << Value; } Line 1, if uncommented complains saying expression did not evaluate to a constant. However Line 2 works fine. What am I missing here?
Line 1. " evaluation operation count exceeds limit of 33554432". It seems like the compiler bails out because the computation is too long. What compiler are you using? Maybe it is getting the same problem and deciding thatFibcan't be evaluated at compile time. See godbolt.org/z/f9fo3fb1fFib(n)--exponentially many inn, in fact. The compiler is only willing to go so far in evaluatingconstexprfunctions.forloop that runsntimes, computing one additional value in the sequence each time. O(n) time, O(1) additional storage, veryconstexpr-friendly. (Strictly speaking there's an O(1)/O(1) algorithm but dealing with floating point imprecision is probably more of a headache than living with O(n) for very small n. You overflow a size_t before n=100.)