Omnifarious icon

Demonstration of compile-time vs. runtime evaluation

Omnifarious | PRO | 12/24/11 08:20:08 PM UTC | 0 ⭐ | 382 👁️ | Never ⏰ | []
C++ |

520 B

|

None

|

0 👍

/

0 👎

#include <iostream>
 
constexpr unsigned long long fib(unsigned short num)
{
   return ((num == 0) ? 1 : (
              (num == 1) ? 1 : (
                 fib(num - 2) + fib(num - 1))));
}
 
int main()
{
   using ::std::cout;
   constexpr unsigned short val = 46;
   // Since result is constexpr, it MUST be computed at compile-time.
   constexpr unsigned long long result = fib(val);
   cout << "fib(" << val << ") == " << fib(val) << '\n';
   cout << "fib(" << val << ") == " << result << '\n';
   return 0;
}

Comments