Skip to content

cpp.php: The fibonacci example needs revision #44

Description

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.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions