Search code examples
c++c++17fibonaccistatic-assert

Computing fibonacci in c++ function and throwing compile-time error


I need to write this function fibo. If the number is too big it should be shown as compile error (the last line of main function) The main function should stay like it is. Any suggestions?

#include <iostream>

int fibo(int n)
{
    if (n <= 1)
        return n;
    //if (n>=300) throws ... ?
    return fibo(n - 1) + fibo(n - 2);
}

int main()
{
    static_assert(fibo(7) == 34);
    const int k = fibo(9);
    std::cout << k << std::endl;
    const int l = fibo(300); // 300th Fibonacci number is large for int
}

Solution

  • You can make fibo a constexpr function, and then throw if the argument is invalid. The throw in a constexpr function will lead to a compile time error if fibo is evaluated at compile time, and a run time error otherwise:

    constexpr int fibo(int n)
    {
        if (n >= 300) throw;
        if (n <= 1) return n; 
        return fibo(n-1) + fibo(n-2); 
    }
    

    and you can use it like this:

    int j = fibo(300);             // run time error
    constexpr int k = fibo(300);   // compile time error
    

    Here's a demo.

    Note that you can't static_assert inside the definition of fibo since the condition depends on the function argument, which is not a constant expression.