Search code examples
cmacrosfibonacci

Is it possible to calculate Fibonacci sequence by preprocessor directives in C?


Just for personal study and better understanding of C code preprocessor 😳:

I am wondering if it is possible to implement Fibonacci function by preprocessor directives in C language.

Normal definition of Fibonacci function could be:

int f(int i) {  // i should be non-negative integer
    if (i <= 1) {
        return 1;
    }
    return f(i - 1) + f(i - 2);
}

The approach of using the template metaprogramming technique in C++ is not what I need.


It seems that it is not possible to perform recursive calculations by using the code preprocessor?


Solution

  • I do not think macro in C can support recursive macro. But Fibonacci is possible macro. By using the fomular of nth number

    #define Fibonacci(n) (POW(1+POW(5,1/2),n) - POW(1-POW(5,1/2),n))/POW(5,1/2)