Reference:
// bad_fibonacci.c
int fibonacci(int n) {
if (n <= 1)
return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
$ clang -c bad_fibonacci.c
bad_fibonacci.c:4:12: error: implicit declaration of function 'fibonacci' is invalid in C99
bad_fibonacci did not declare the function fibonacci before using it which resulted in an error.
// good_fibonacci.c
int fibonacci(int n);
int fibonacci(int n) {
if (n <= 1)
return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
Adding the declaration allows the compiler to work in one pass.
$ clang -c good_fibonacci.c // It worked
The bad_fibonacci.c file compiles successfully, and there is no implicit declaration of the function fibonacci. Within the function body, the prototype of fibonacci is already known, so calls like fibonacci(n - 1) are valid. Therefore, the additional declaration in good_fibonacci.c is redundant.
Related: Comment on Hacker News:
I found the section on forward declarations at least partially off. I have never needed to use forward declarations for single recursion like the fibonacci example he gave. Mutual recursion does of course require forward declarations.
Reference:
The
bad_fibonacci.cfile compiles successfully, and there is no implicit declaration of the functionfibonacci. Within the function body, the prototype offibonacciis already known, so calls likefibonacci(n - 1)are valid. Therefore, the additional declaration ingood_fibonacci.cis redundant.Related: Comment on Hacker News: