yeahboy yeahboy - 1 year ago 52
C Question

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){
unsigned long long result = 1;
unsigned long long aux = 0;

while (n > 1){
result += aux;
aux = result;

It returned this


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?

Answer Source

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.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download