C++ constexpr compiles too fast

64 views Asked by At

When I compile a program including:

#include <iostream>
using namespace std;
constexpr int fib_c(int n)
  {
   if (n<=1) return n;
   return fib_c(n-1)+fib_c(n-2);
  }

int main()
 {
  constexpr int result_c = fib_c(45);
  cout << result_c << "\n";
  return 0;
 }

g++ -O3 (version 5.1.0) compiles in 1.2 seconds. It runs in 0 seconds. But it runs in 7.5 seconds when result_c is not declared constexpr.

How can the compilation be so fast? Shouldn't it take at least 7.5 seconds to do what my optimized compiled code does just to get the same value? Why doesn't the compiler generate for me code as fast as the code the compiler generates for itself?

By the way, this problem has been solved by g++ version 10.2.1 in an interesting way: now it fails to compile no matter how high I set -fconstexpr-ops-limit, at least up to any limit I can bear the compilation time. So, what magic code did they take out to slow down constexpr evaluation between versions 5.1.0 and 10.2.1?

0

There are 0 answers