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
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.
The following code gives output as 0 0 0 0 using Codeblocks.
int main()
{
static int i=5;
if(--i){
main();
printf("%d ",i);
}
}
I perfectly understands how the above code executes. However, when I removed 'static' from the code and used int i = 5, Ideone.com(online compiler) gave me runtime error and Codeblocks(using GCC) gave me nothing- even the terminal does not pop up.
I also tried placing the declaration part outside main i.e., static int i; and in main, I then gave i = 5;. Still, I am getting the above errors. I have no idea what is happening. Any help would be greatly appreciated.
PS: The program was found on a website and no explanation was given there.
If you remove the static that each call to main gets its own copy of i, initialized to 5, and so your recursion never terminates.
When you declare static int i outside main() and initializing it inside main() to value 5 has a problem when you execute. For the first time if(4) makes it call your inner main() which executes outer main() making i set back to 5 leading it to infinite loop, hence no output you see because your if never fails and only one possibility it has is if(4).
int main() // 1st main call
{
static int i=5;
if(--i){ // if(4), if(3), if(2), if(1)-> all four if's are true
// if(0) fails
main(); // 2nd main, 3rd main, 4th main, 5th main -> corresponding to
// above successful if's.
// When if(0), recursion ends, return
printf("%d ",i); // Now i is `0` and prints 4 zero's
}
}
If you remove static, you get an infinite recursion before you output anything. The recursion leads to a stack overflow, and the program crashes.
The static means you operate always on the same variable, so you can count from 5 -> 0. if you remove it, you initialize it at every call with 5, and if(4) is always true.
With static it is only initialized once.
when using static printf will show 4,3,2,1 and the recursion will end.
when not using static, theoretically (if the program would run) the printf will show 4,4,4,4..
and the recursion will never end.
There is no problem in your code.
CASE 1:
if you write, it will give you output 0000 cause very time the you are decrementing the value of i. once it become 0. if condition will be false and it will print 0 four times.
int main()
{
static int i=5;
if(--i){
main();
printf("%d ",i);
}
}
CASE 2:
but if you remove the static, the in every recursive call you are creating a new variable i which will take 2 byte each time and consume memory(in stack). Once the stack full, it prompt runtime error and program will be crashed. The online compiler of http://ideone.com
handle the runtime error in backend so that your program will not crashed.that why you are getting runtime error. and expected answer.
CASE 3:
and when you declare your variable outside like
static int i;
int main()
{
i=5;
if(--i){
main();
printf("%d ",i);
}
}
In this case it will again cross the memory limit. here each time you are assigning the 5 to i and main() will take space in stack, again program crash.
This question already has answers here:
unexpected output in C (recursion)
(3 answers)
Closed 8 years ago.
I executed this program and am unable to understand why the output is "0" four times. Can anybody help me understand how it works? I do not understand why "printf" executes when the condition fails and why it executes four times.
int main()
{
static int i=5;
if(--i)
{
main();
printf("%d ",i);
}
}
Your main function prints 4 times 0 because the printf statement occurs after the recursive call and i is a static variable. A static variable is initialised only once and it is not destroyed after the function terminates since it is not allocated into the function stack.
As result, the value of i used by the printf is always 0 as i is decremented each time main is called and the first printf function is executed after the deepest function has returned because i=0.
To better understand this solution, let's look at the stack call :
main() i=5 (First call)
if(4) // True
main() (Second call)
if(3) // True
main() (Third call)
if(2) // True
main() (Forth call)
if(1) // True
main() (Fifth call)
if(0) //False End recursion No print because the condition is false
return
print(i) // 0 (Forth Call)
print(i) // 0 (Third call)
printf(i) // 0 (Second call)
print(i) // 0 (First call)
The main is called 5 times but the application prints 4 zeros because the the last call does not print anything as the if condition is false.
i is static so it is initialized only once. Every time you call main it is decremented when i == 1 then the `if statement condition will be false here:
if(--i)
the recursion will stop and i will be 0, the recursion will then unwind and the program will print four 0s.
For completeness sake, the draft C99 standard section 6.2.4 Storage durations of objects paragraph 3 says(emphasis mine):
An object whose identifier is declared with external or internal linkage, or with the
storage-class specifier static has static storage duration. Its lifetime is the entire
execution of the program and its stored value is initialized only once, prior to program
startup.
This question already has answers here:
unexpected output in C (recursion)
(3 answers)
Closed 8 years ago.
I executed this program and am unable to understand why the output is "0" four times. Can anybody help me understand how it works? I do not understand why "printf" executes when the condition fails and why it executes four times.
int main()
{
static int i=5;
if(--i)
{
main();
printf("%d ",i);
}
}
Your main function prints 4 times 0 because the printf statement occurs after the recursive call and i is a static variable. A static variable is initialised only once and it is not destroyed after the function terminates since it is not allocated into the function stack.
As result, the value of i used by the printf is always 0 as i is decremented each time main is called and the first printf function is executed after the deepest function has returned because i=0.
To better understand this solution, let's look at the stack call :
main() i=5 (First call)
if(4) // True
main() (Second call)
if(3) // True
main() (Third call)
if(2) // True
main() (Forth call)
if(1) // True
main() (Fifth call)
if(0) //False End recursion No print because the condition is false
return
print(i) // 0 (Forth Call)
print(i) // 0 (Third call)
printf(i) // 0 (Second call)
print(i) // 0 (First call)
The main is called 5 times but the application prints 4 zeros because the the last call does not print anything as the if condition is false.
i is static so it is initialized only once. Every time you call main it is decremented when i == 1 then the `if statement condition will be false here:
if(--i)
the recursion will stop and i will be 0, the recursion will then unwind and the program will print four 0s.
For completeness sake, the draft C99 standard section 6.2.4 Storage durations of objects paragraph 3 says(emphasis mine):
An object whose identifier is declared with external or internal linkage, or with the
storage-class specifier static has static storage duration. Its lifetime is the entire
execution of the program and its stored value is initialized only once, prior to program
startup.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is really happening in this code?
I have a code which includes a recursive function. I have wasted a lot of time on recursion, but i still couldn't get it, really:
#include<stdio.h>
count(int);
main(){
int x=10,z;
z=count(x);
}
count(int m){
if(m>0)
return count(m-1);
}
When count is called for the first time with argument 10, it fulfils the condition and the recursion starts. What happens really when a function calls itself? I dont get it. What does the statement return count(m-1) mean? Where does it tranfer the control?
The return value of the function count is undefined, because there is no default return if (m <= 0) is true.
C11, ยง 6.9.1 Function definitions
If the } that terminates a function is reached, and the value of the
function call is used by the caller, the behavior is undefined.
Besides, to understand how a recursive function works, you have to take a paper and try to execute the code by yourself (see also here).
You need count to return something when m <= 0. You should declare the return type of count and compile with -Wall so the compiler will help you find mistakes in your code.
recursion means that the function will call itself, mostly at the end of itself, if it's tail recursion.
So your count function checks that the input argument is > 0 and then if it is, it will call count(m-1). Now it starts at the top of count with m=9. It does the same thing, and then calls count with m=8, etc.
Until the end condition is reached, which should normally be explicitly catered for in your function, such as if (m == 0) return m; or some such thing. At that point the recursion ends and the function terminates.
Also, count should have a return type, such as int count (int m)
what does the statement return count(m-1) mean ? where does it tranfer the control?
That seems to be your only question.
it means that it is calling "count" with the value m-1. So if m was 10, then it is calling "count" with 9.
It is transferring the control recursively to the count method.
You also don't have a return for the every possible path in the "count" method.
What happens if m is <= 0?