Shikhar Yadav
Shikhar Yadav

Reputation: 23

What happens if return is not used in a Recursive Return Function?

#include <stdio.h>
int lcm(int ,int );
int main()
{
   int a,b,f;
   printf("Enter the numbers:");
   scanf("%d %d",&a,&b);
   f=lcm(a,b);
   printf("LCM of %d and %d : %d",a,b,f);
   return 0;
}

int lcm(int a,int b)
{
    static int x=1;
    if(x%a==0 && x%b==0)
        return x;
    x++;
    lcm(a,b);
}

Now, this code isn't giving any error ... and giving me correct answer but how the value is being return to main function without the return keyboard in lcm function " lcm(a,b); " !! Please Explain !!

Upvotes: 1

Views: 193

Answers (1)

P.P
P.P

Reputation: 121357

Now, this code isn't giving any error ... and giving me correct answer but how the value is being return to main function without the return keyboard in lcm function lcm(a,b);

C language allows incorrect code and lets you shoot yourself in the foot. This is called undefined behaviour. Your code exhibits undfined behaviour for any arguments except (1,1). When you pass (1,1) the first return is triggered for the very first time.

You should read What Every C Programmer Should Know About Undefined Behavior for some detailed explanation with examples.

Having said that, it's not undefined behaviour to ignore the return value per se. It's only undefined the caller uses the return value from the function. For example, your already ignores the return values of scanf() and printf() functions in your code yet they are valid. Although, you should check the return value of scanf() to if the scanning was successful! On a relevant note, scanf() use is discouraged in C as it's error prone.

But in your code, you do use the return value (f=lcm(a,b);). Hence, there's undefined behaviour (with the one above stated exception).

But if you were to write the call to lcm() main as:

 scanf("%d %d",&a,&b);
 lcm(a,b);
 ...

then there won't be any undefined behaviour (although it won't be useful in your program).

Upvotes: 2

Related Questions