Explain the reason for such output of this C program - c

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.

Related

Can someone explain output of this C program? [duplicate]

This question already has answers here:
unexpected output in C (recursion)
(3 answers)
Closed 4 years ago.
#include <stdio.h>
int main()
{
static int i = 5;
if (--i)
{
main();
printf("%d\n", i); // will this line executes ?
}
return 0;
}
Output:
0
0
0
0
does code below main(); printf statement instructions is placed to stack every time when main recursive calls happens and executed while terminated from this program?
i is reduced by successive calls to main until zero is reached.
Then printf is called for each level of recursion.
(Note that the behaviour of calling main from itself is well-defined although ill-advised in C, in C++ the behaviour is undefined.)
if (--i)
This will evaluate true the first time (--i == 4). The code recurses into main(). (Recursion: A function calling itself.)
As i is static, it will retain its value of 4 (as opposed to an automatic variable, which would be initialized to 5 again). The if (--i) in this second execution of main() will again be true (evaluating to 3), and will again call main() (for a third execution of the function).
The same for --i == 2 and --i == 1, for four executions of main() (including the first, non-recursive one) total that are evaluating the if condition to true.
The next recursion will evaluate the if condition to --i == 0, and thus false. Skipping the if clause, the function call will just return. i is zero at this point, and -- being static, i.e. only one persistent i for all instances of main() -- will remain at that value.
The main() call one level up the stack -- the one that evaluated --i == 1, then called main() and was waiting for it to return -- will now continue with the statement after the call to main(), and printf() the current value of i... which is 0.
The same happens three more times (for a total of four) until the top-most main() returns. You get four times the current value of i, which is 0.
Note that calling main() from your program is allowed in C, but not in C++. This is specifically for calling main() recursively; for other functions, it is allowed in either language.
(--i) will decrease the value of i to 4 when it is called for the first time and it will continue the decrement of i until (i==0) due to recursion.
Since you have declared the variable i with static keyword and hence a single memory is allocated to it and all the changes are reflected back to it

Using recursive functions in C, why is the output of the following program 012345?

I used the concept of recursive function in the following but from my understanding of the concept, the output of the code should be 0, but the output here is 012345 and I'm not sure how it is working.
Could someone please explain it to me as my College Professor couldn't do so.
#include<stdio.h>
#include<conio.h>
int yo(int a)
{
if(a>0)
{
yo(a-1); //using recursion function
}
printf("%d",a); //printing value
}
void main()
{
yo(5);
getch();
}
The printf is after the recursive call; Hence, the "stack" of a-values with which yo is called is 5,4,3,2,1,0, before the last yo-call with parameter value 0 begins to print; then 1,2,...
Use a debugger and try it out!
first the value of a is 5 when function is called, so this value is stored into stack and condition is checked (5>0) which is true, so next time yo() is called with value 4 and same procedure is repeated until the value of a becomes 0.
now condition is false (0>0), so next statement will be printed with value of a in stack and in stack value is pop like last in first out and will print 012345.

C program recursive call to main() with and without parameters

Why does it give an error of segmentation fault(core dumped) and gives no output in 1st case ?Can anyone explain how program is program callls main recursively with parameters?
#include <stdio.h>
int main()
{
static int i = 2;
if (i<7)
{
main();
printf("%d ", i);
i++;
//main(10);
}
}
-
#include <stdio.h>
int main()
{
static int i = 5;
if (--i)
{
//main();
printf("%d ", i);
main(10);
}
}
You are calling main() first and then incrementing i
if (i<7)
{
main(); // <-- main called when i still 2
printf("%d ", i);
i++; // <-- statement never reached
//main(10);
}
Hence, while main() calls main() recursively, the statement i++ is never reached.
You should increment i before calling main()
if (i<7)
{
i++;
main();
printf("%d ", i);
//main(10);
}
1st case the i++ after the call of main(), that means the program has no chance to add the i, and into infinity loop, and stackoverflow! haha....
but the 2nd case, it's reduce the i before you call the main.
TL;DR StackOverflow (Pun or no pun, it's true both ways).
First: Some important information
This case has nothing to do with passing an argument to main() or not. Actually, as per the latest C standard, C11, for a hosted environment, the conforming signature of main() is int main(void) and following that, main(10); is wrong, altogether.
Now, coming to the actual problem here,
In the first case, change of i value happens after the call to main(), so in effect, the value of i never get changed because the control never reaches the statement which modifies i. Hence, it's an infinite loop, and because of the recursive call to main(), stack overflow happens.
In later case, i value gets updated before call to main(), so that value actually reflects. Thus, at some point (after 4 occurrences, actually), the if condition meets a FALSE condition and the recursive call ends and the stack unwinds.
First case:
i++ is positionned after the call to main. So i will always be equal to 2, as you never reach this part of the code. You are then calling your main function everytime, leading to an infinite recursion, and thus to the segmentation fault. The fix for this case would be to increase i before calling the main function.
if (i<7)
{
i++; // Increment before calling the main function, so i value is changed
main();
printf("%d ", i);
}
Do note that it will lead to something which looks like your second case, except that you will print several "7".
Seconde case:
In the second case, you are decreasing the value of i everytime you enter your if condition. When you finally can't enter your if condition anymore, it means i is equal to 0 (as if(0) is equivalent to if(false)). Everytime you will return to the previous called main function, i will still be equal to 0, explaining why you are displaying "0" everytime. If you want to print the different values, you can place your printf before the call to the main function for instance.
In the first case:
"i" is never incremented therefore you run in an infinite loop and get an overflow.
In the second case:
You call the recursion before displaying the value of "i", after four calls "i" equals to 0 and your recursion stack unwinds.
Modify your condition and perform outputs before the recursion call.
In the first case, i is never incremented, hence, the main keeps getting called and soon enough there is no more stack memory available to the program.
In the second case, the last updated value of i is intact throughout the lifetime of i. As i is static, program is referring to the same memory address on all the iterations. While printing i you see the last updated value, that is 0, as output.

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());

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

Resources