C programming doubts- function call inside function call - c

#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.

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

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 :)

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.

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*/

Related

confusion about static int and calling them in printf

Please test this code and give me your answers :
#include <stdio.h>
int func() {
static int n = 0;
n++;
return n;
}
int main() {
/*int first = func();
int second = func();*/
printf(" first call : %d \n second call : %d ",func(),func());
return 0;
}
Logically it should print 1 and 2 but it is printing 2 and 1 .
If you Un-Comment the comments and print the variables "first" and "second" , the problem is solved!
What is happening?
thank you already!
The order in which a function call's arguments are evaluated is unspecified, i.e., the compiler is free to make the two func() calls in any order before passing the return values to printf. If you first assign the results to variables, obviously you get to decide in which order they are used.
The order in which the parameters to a function are passed is not defined in the standard, and is determined by the calling convention used by the compiler. I think in your case, cdecl calling convention (which many C compilers use for x86 architecture) is used in which arguments in a function get evaluated from right to left.
because while calling the function it takes right associative..
i.e, the last one in printf gets called first then the before one.. thats why it is printing 2 then 1.
try using two print statements like:
printf("First call: %d\n",func());
printf("second call: %d\n",func());

Using It's Own Call as One The Parameters in a Function call statement

Here Is my code:
#include <stdio.h>
int mul(int,int);
int main()
{
int sum,m,n;
scanf("%d%d",&m,&n);
sum=mul(10,mul(m,n));
printf("%d",sum);
}
int mul(int x,int y)
{
int sum;
sum=x+y;
return(sum);
}
Input
10
5
Output
25
Can someone tell me why I get 25 as output? Was the function called 2 times?
One during parameters and other time during sum?
It's perfectly simple:
sum=mul(10,mul(m,n));
You're calling mul() with 10 as the first argument, and the return value of mul(m, n) as the second argument.
m and n are 10 and 5, so mul(10, 5) returns 15. The statement in your main function then evaluates to this:
sum = mul(10, 15);
Which is 25.
TL;DR: yes, mul() is called twice. Once with m and n as arguments. The second time with the sum of m and n, adding 10
Using a debugger, or even looking at the assembler output generated by the compiler would've told you there were 2 successive calls to mul.
And yes, as others have rightfully pointed out: reading the help section (in particular how to ask) would be a good idea. It explains that you're expected to do the sensible debugging/diagnostic steps yourself. Only if that didn't solve the problem should you post a question here:
Explain how you encountered the problem you're trying to solve, and any difficulties that have prevented you from solving it yourself.
You merely state that, given input X, you get output Y, and you don't know why.

Understanding recursion function call

Where will the value of n be stored after first call to factorial()?
When n=1 then return 1 is sent, why doesn't res becomes equal to 1 in main function?
#include<stdio.h>
int factorial(int n)
{
if(n<=1)
return 1;
else
return n*factorial(n-1);
}
int main()
{
int res =factorial(3);
printf("%d",res) ;
}
The run-time stack will have four functions in total: main(), factorial(3), factorial(2), and factorial(1). Each of these gets its own variable space. There are three instances of the variable n, one for each call to factorial.
When factorial(1) returns 1, that value isn't returned to main(), because main() is not what called it: factorial(2) called it. That instance performs the operation 2*1 and returns 2. The caller of that instance is factorial(3), which receives the 2, performs the operation 3*2, and returns a value of 6 to its caller, main().
Does that help clear it up? If not, I have two suggestions:
(1) Search this topic on StackOverflow and the internet in general; there are plenty of detailed walk-through examples of factorial.
(2) Insert print statements to trace the flow of data and execution. Within factorial, separate the computation and the return, so you can put a print in between:
catch = factorial(n-1)
result = n * catch
print n, catch, result
return result
Each time a function is called, its parameter and local variables are pushed onto the stack. In the case of a recursive function, there will be a set of the variables on the stack for each active invocation of the function.
In this example, the first call to factorial has n set to 3. Within the function, factorial is called again, this time with n set to 2. It calls itself one more time with n set to 1. In this last call, it returns a value of 1. This gets returned to the prior invocation where n is 2, which then returns 2 * 1 which is 2. This value is returned to the first invocation where n is 3 and returns 3*2 which is 6 back to main.
So the call stack looks like this:
main
|--> factorial(n==3)
|--> factorial(n==2)
|--> factorial(n==1)
return 1
return 2*1
return 3*2
print 6
n is not stored in the way of global or static variables - it's stored on the stack. Calling a function with arguments the arguments are being pushed on the stack.
See what's happening when your running your program:
factorial(3) gets called (in main)
As n is not equal or smaller to 1 factorial(2) is called and the result will be multiplied by n (is 3).
As n is not equal or smaller to 1 factorial(1) is called and the result will be multiplied by n (is 2).
As n is now equal or smaller to 1 the function returns 1
factorial(2) returns 1*2
factorial(3) returns 2*3
res will be 6

Explain the reason for such output of this C program

Please help me to understand the output of the following C program.
#include "stdio.h"
int fun(int x)
{
static int a=0;
return x+a++;
}
int main()
{
int i;
for(i=0;i<5;++i)
printf("%d ",fun(printf("%d",0)));
return 0;
}
output is : 01 02 03 04 05
why not : 1 2 3 4 5
The first 0 is the result of the execution of the printf() statement inside the fun() function call
fun(printf("%d",0))
and the second 1 is the result of the outer printf() which prints the return value of the fun() function call. The fun() function call sends the return value of the inner printf() which is always 1, and since you have initialized the variable a as static the value of a remains same and is added everytime with the function call.
since you are always printing 0 in the printf() inside the fun() function call, hence the 0 before the numbers.
The arguments are evaluated in order when you call printf here:
printf("%d ",fun(printf("%d",0)));
The outer printf call needs to evaluate all its arguments, which is the following:
fun(printf("%d",0))
Which then calls the inner printf to evaluate all of its arguments.
First, printf("%d",0) will be evaluated, and evaluate to the number of characters printed (since this is what printf() returns). This is passed to fun next, which will return the number of characters the printf printed (1) plus the number of times it has been called (due to the static int a). That will then be passed to the outer printf, printing the second number, then a space.
The reason is that in this statement
printf("%d ",fun(printf("%d",0)));
function printf is called twice. At first it is called as the argument expression of function fun
fun(printf("%d",0))
and outputs aways 0.
The second time the function is called with the resut of the call of function fun Take into account that the value of call
printf("%d",0)
is always equal to 1.
imagine your commands in the way that it is evaluated:
printf("%d ",fun(printf("%d",0)));
is equivalent to:
int printf_result = printf("%d",0);
int fun_result = fun(printf_result);
printf(("%d ",fun_result);
this is c. this is not python or matlab. if you assign the result value it doesn't influence the effects of the function call.

Why does this recursive function loop infinitely rather than printing numbers in reverse?

int reverse(int);
void main()
{
int no =5;
reverse(no);
}
int reverse(int no)
{
if(no == 0)
return 0;
else
printf("%d",no);
reverse(no--);
}
This program goes in infinite loop.Why is that so? I am not able to get the desired ouput.
Desired output should be 5 4 3 2 1.Thank you in advance
In this recursive call:
reverse(no--);
You are passing the value of no--. Since this uses the postfix -- operator, this means "decrement no, then pass the original value of no into the recursive call to reverse." This causes infinite recursion, since you are constantly making a recursive call with reverse set to the same value.
To fix this, change this to read
reverse(no - 1);
Notice that there's no reason to decrement no here, since within the current recursive call you will never read no again. You can just pass the value of no - 1 into the function. In fact, you might want to in general avoid using -- in recursive calls, since it almost always indicates an error in the code.
Hope this helps!
You're using the post-decrement operator on no. That first gets the value of no and uses that as the value of the expression and then decrements no (still using the undecremented value as the value of the expression). You probably want to use --no or even just no - 1. (The former will modify no, whereas the latter will not, but it does not matter because no is not referenced after that point.)
Change:
reverse(no--);
to:
reverse(no-1);
no-- returns the original value before the decrement occurred. So this line will always call reverse(5). Hence, infinite loop.
n-- is post increment which first use n as argument of the function and then decrement n.
So n-- essentially does is
reverse(n);
n = n - 1;
What you want is --n
You are using post-decrement. First evaluates, then reduces value.
Change this:
reverse(no--);
to this:
return reverse(--no);
--no is pre-decrement. First decrease "no", then pass the value to reverse.
Note that I'm RETURNING the result value, you function always have to return an int, due to its declaration.
You want to do
int reverse(int);
int main()
{
int no =5;
reverse(no);
}
int reverse(int no)
{
if(no == 0)
return 0;
else
printf("%d",no);
return reverse(--no);
}
So that you're returning a number every time you call reverse and you decrement no before you use it.

Resources