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());
Related
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.
I am trying to understand the following program in which successive recursion function calls are present, but getting confused while tracing how the tack gets loaded.
void func(char*); // function prototype
int main(){
func("123");
return 0;
}
void func(char a[]){
if(a[1]=='\0')
return;
func(a+1);
func(a+1);
printf("%c",a[1]);
}
the output for this is 3 3 2
would appreciate if someone could advise on this one...
does this kind of multiple recursive calls beneficial in any way or find application in specific problem areas..?
Just put yourself in the position of the CPU and step through line-by-line (or use a debugger to help with that task).
The first call is to
func("123")
this call does not satisfy the termination condition a[1] == '\0', so it calls
func("23");
The call to func("23") in turn calls
func("3")
which DOES satisfy the return condition. So, that call returns to the previous caller, func("23").
func("23") proceeds to make another call to func("3") due to the lines
func(a+1);
func(a+1);
Continue this process of executing the program in your mind, and write down what would be in each call to printf. That will explain your output.
UPDATE
Note that the call to printf() happens after the recursive calls, so e.g. a call to
func("123")
would proceed like
Enter func("123")
Termination condition not met
Call func("23")
Call func("23") again
Printf("3") (which is a[1])
Return
Debugging with breakpoints is one way to understand recursion. Another way is to draw the tree of recursive calls.
From the figure, In every level after level0, the printf statement occurs after every two nodes owing to these two lines of code:
func(a+1);
func(a+1);
In general, this becomes a perfect binary tree for any input string of length greater than 0. The total number of nodes is given by this formula:
2^(k+1) - 1 // k is the depth; here k = 2
Total number of printf statements executed can be obtained by this formula:
2^k - 1 // For k=2, there will be 3 printf statements each printing 3,3,2 respectively
the posted code is a rather poorly designed instance of recursion.
The following code has the correct 'tail' form of recursion.
It could be made even better by passing the reversed string back to main and let main print it.
It reverses the order of the string passed to func() by main()
Please, when asking about a runtime problem, post code the compiles, including the necessary #includes for header files so we are not guessing about which headers to include
#include <stdio.h>
void func(char*); // function prototype
int main(){
func("123");
return 0;
}
void func(char a[])
{
if(a[1]=='\0') // check for end of recursive sequence
{
printf( "%c", a[0] ); // last tail action
return;
}
func(a+1); // step+next recursion
printf( "%c", a[0] ); // tail action
return;
}
The recursion can be simply understood as follows.
For example:
Func(int a){
while(a>1)
return a * func(a-1);
}
Suppose a = 5.
What happens is that it returns 5 * func(4).
Now func(4) returns 4 * func(3) and it goes on like this.
Check out this example for use of recursion in fibonacci series.
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.
This documentation gives an example of how to write a varargs function, printf() .
As the documentation, printf() will find the first % in the string and use va_arg(argp, int) to get the first argument pointer; find the second % in the string and use va_arg(argp, int) again to get the second argument pointer......
So, I wrote a code snippet:
int Var = 0;
int Func (int X)
{
Var = Var + X;
return Var;
}
int main (void)
{
printf ("%d\n%d", Func (3), Func (5));
}
It will print:
8 <-- 5+3
5 <-- 5
I know calling multiple functions in printf() is undefined behavior, but why not print:
3 <-- 3
8 <-- 3+5
just as the sample code in that documentation?
ps: If my question is not clear, please help me edit it. Thanks
The order that function parameters are evaluated in C is platform dependent (not undefined, just unspecified).
See this blog that talks about it: Funny thing about C parameter evaluation order…
If you want to force the order, you would call Func() before the printf():
int a = Func(3);
int b = Func(5);
printf("%d\n%d", a, b);
While it's true that parameter evaluation order isn't defined, parameter placement is. The so called C calling convention states that parameters are pushed to the stack from right to left. This order is needed precisely to support variable parameter functions. Normally, as each parameter is evaluated, it is inmediately pushed into the stack (although some obscure optimizations in order to optimize memory writes might alter this), so we could expect that parameter evaluarion works by evaluating them from right to left.
That would mean that Func(5) is first evaluated, pushes 5 into the stack, then Func(3) is evaluated, pushing 8 to the stack. Parameter order, as it will be printed by printf are 8 and 5.
I have a recursive program. When the printf is used in the function, it outputs 123 and when used outside, it outputs 0123 .
#include <stdio.h>
fact(int);
int main()
{
int x=3;
fact(x);
printf("\n");
system("PAUSE");
}
int fact(int y)
{
if (y > 0)
{
fact(y-1);
printf("%d",y);
}
//printf("%d",y);
}
I am not using both the printf at the same time . What difference does the location of this printf statement create?
Since your if condition looks for the values greater than zero, it is working as expected.
When the printf outside that IF block is used, it gets executed even when y is 0, which is not the case for the printf inside the IF block.
fact(int) is called by following sequence,
fact(3)-->fact(2)--->fact(1)--->fact(0)
The last call is fact(0). According to the implementation of fact(int), when 0 is passed in, 0 is printed if printf() is used outsite. 0 is not printed if printf() is used inside.
In fact, all the values passed into fact(int) is printed when printf() is used outsite.
I'd say one reason you didn't see the answer yourself is because your code is sloppy. Here are some complaints:
Your functions have no explicit return statements which are
especially important for understanding recursive code.
system() requires stdlib, but stdlib.h isn't included.
system("PAUSE") is unportable and unnecessary. Actually your code
would not run on my system because of this. See:
http://www.gidnetwork.com/b-61.html
Your question looks like homework, so this one is the homework's fault and not yours: because n! grows so quickly, factorial functions using 'int' for the return type can only calculate n! for 1<=n<=12, which is useless.
Try this exercise: write a one-line factorial function using a single return and a conditional assignment.