简体   繁体   中英

C function returns correct result but no return statement is given, why?

So I've written a function that should return the n'th Fibonnacci number, but I forgot to actually return my result. I did get the " control reaches end of non-void function" warning, but the code executed fine and returned the correct result. Why is that? How does C know that it should return "result"?

int fib (int n);

int main(int argc, char** argv) {
    printf("%d", fib(10));

}

int fib (int n){
   if (n == 1){
      return 1;
   }
   if (n == 0){
     return 0
   }
   fib(n-2) + fib(n-1)
}

It returned this

55

I've tried to add

 int j = n+1

to the last line of the function, and then it actually returned 2, not 256. Is this a bug, or how does c read something like this?

Reaching the end of a non void function without a return statement invokes undefined behavior. Getting the expected result is a form of undefined behavior commonly called luck . By the way, 256 may be what you expected, but it is not correct .

A possible explanation is: the last value computed by the function and stored into the register that would normally contain the return value is the expected result.

Of course you should never rely on this, nor expect it.

This is a good example of the use of compiler warnings: do not ignore them. Always turn on more compiler warnings and fix the code. gcc -Wall -W or clang -Weverything can spot many silly mistakes and save hours of debugging.

Here are some other problems:

  • you do not include <stdio.h>
  • you compute an unsigned long long but only return a probably smaller type int
  • your algorithm computes powers of 2, not Fibonacci numbers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM