Tom
Tom

Reputation: 125

C programming doubts- function call inside function call

#include<stdio.h>

find(int x, int y)
{
    return((x<y)?0:(x-y));
}

int main(void) 
{
   int a=find(5,find(5,4));
   printf("%d",a);

   return 0;
}

The above program gives output as 4. I ran with different values and learnt that the code snippet is to find minumum of two numbers. But, I can't seem to understand how it is working. Can someone explain it for me? I know how the ternary operator works, I didn't get the function call inside function call part.

Upvotes: 2

Views: 185

Answers (4)

mfs
mfs

Reputation: 4074

Try to break it. See it this way.

when you say int a=find(5,find(5,4)); then the find function inside the find function i.e find(5,4) returns 1; Now the resultant value makes it int a=find(5, 1); And when find find(5,1); is called it returns 4 :)

Upvotes: 2

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

To add to the previously given answers, it is always better to explicitly specify the return type of a function.

Change your find() function signature to

int find(int x, int y);

Next, regarding the function execution order, the flow is inside-out, means, the inner function will be executed first, the return value will be used to execute the outer call.

Diagramatically,

 int a=find(5,find(5,4));

can be decomposed as

 int a=find(5,find(5,4));       //consider step 1.0

           |                   /*inner find() executes first, returns 1*/
           V

     int a=find(5, 1 /*result of find(5,4)*/);       //consider step 1.1

                 |                  /*result of inner find() used for outer find()*/
                 V

         int a=find(5, 1));       //consider step 1.2

                 |              /*outer find() executes second, returns 4*/
                 V

               int a= 4;       //consider step 1.3
                               /* value 4 is assigned to a*/

Upvotes: 1

unwind
unwind

Reputation: 399703

What's there to "get"?

The function call is, like any other call, evaluated "inside out". All the argument values must be known before the call is made. So, the second argument is find(5,4), thus that call happens first. Then the value of that call is used as an argument in the second, outer, call.

Upvotes: 1

Gopi
Gopi

Reputation: 19864

int a=find(5,find(5,4));

find(5,4) returns 1

find(5,1) returns 4

First the find() function gets executed with 5 and 4 as its paramters. which will cause x<y condition to fail and returns x-y which is 5-4 =1

Later you have find(5,1) which again makes the x<y condition fail returning 5-1 which is 4

Upvotes: 2

Related Questions