I am really new to programming (I’m an electronics and comm. engineer) and I am not able to figure out why one program works and the other one doesn’t.
I’d like to get a good understanding of recursive functions before going any further with my learning. I would appreciate any help regarding this.
I know the difference between the x++ and –x. But in this context of this program, I thought both of these programs should run the same way. But they don’t.
void rec(int x)
{
if(x>0)
rec(x--);
printf("%d",x);
}
int main()
{
rec(4);
_getch();
} /*This doesn't work. And shows a stackoverflow */
void rec(int x)
{
if(x>0)
rec(--x);
printf("%d",x);
}
int main()
{
rec(4);
_getch();
} /*This gives a proper output as expected*/
/*The output is 00123*/
Thanks!
P.S: Forgive me if this is a trivial or stupid question, but I am stuck on this and I thought this is the best place I can look for help.
This will recurse forever (or at least until you exhaust your stack space).
x--means use the current value ofxand then decrement it.In other words, let’s call
recwith the parameter 20. That’s greater than zero, so it will in turn callrecagain with the current value of 20 then decrementx(but effectively after the call returns.Hence you’re forever calling
recwith the value of 20, which is why you’re blowing out your stack.If you change
x--to--x, it decrementsxbefore passing it to the function, hence it will go20, 19, 18, ... 1, 0, at which point it will run back up the stack printing all those values.If you had put a
printf ("before: %d\n", x)before theifstatement, you would have seen a lot of20lines output to the screen.