-1

How this code compiles even though i have not written return in else section?


#include <stdio.h>
int fibo(int n,int a,int b)
{
    int x;
    if(n==1)
    printf("%d\n",b);
    else
    fibo(n-1,a+b,a);//Here
    
}
int main()
{
    int num;
    scanf("%d",&num);
    fibo(num,1,1);
    return 0;
}

or


#include <stdio.h>
int fibo(int n,int a,int b)
{
    int x;
    if(n==1)
    return b;
    else
    fibo(n-1,a+b,a);//Here

}
int main()
{
    int num;
    scanf("%d",&num);
    printf("%d",fibo(num,1,1));
    return 0;
}


I tried many compilers still it returns 13 for input 7.Let's forget about compilation for second,then also how i am getting 13 (in second code) because 13 is returned to parent fibo function and parent fibo function is not returning to its parent,then how in main function value 13 is returned.

Harsh Shah
  • 150
  • 2
  • 6

1 Answers1

1

Your fibo() function is defined as returning an int, but doesn't actually return any values at all. It prints something, but that's a different thing entirely from returning a value.

C allows a function with a non-void return type to not return anything if and only if the return value is ignored where the function is called, which you're doing.

If you instead had

int val = fibo(num, 1, 1);

your code would then exhibit undefined behavior and all sorts of weird things could happen.

Shawn
  • 47,241
  • 3
  • 26
  • 60
  • I have just added another code also.Thank you for your quick response. – Harsh Shah Dec 04 '22 at 13:30
  • @HarshHiteshShah Your new version exhibits that undefined behavior because it tries to use a non-existent returned value. One of the weird things you sometimes get is the appearance of something working. Probably a register that just happens to be used for both function parameter and return values in the ABI your test system is using. – Shawn Dec 04 '22 at 13:39