Advertisement
Omnifarious

Demonstration of compile-time vs. runtime evaluation

Dec 24th, 2011
243
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.52 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. constexpr unsigned long long fib(unsigned short num)
  4. {
  5.    return ((num == 0) ? 1 : (
  6.               (num == 1) ? 1 : (
  7.                  fib(num - 2) + fib(num - 1))));
  8. }
  9.  
  10. int main()
  11. {
  12.    using ::std::cout;
  13.    constexpr unsigned short val = 46;
  14.    // Since result is constexpr, it MUST be computed at compile-time.
  15.    constexpr unsigned long long result = fib(val);
  16.    cout << "fib(" << val << ") == " << fib(val) << '\n';
  17.    cout << "fib(" << val << ") == " << result << '\n';
  18.    return 0;
  19. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement