尽管预增量在此代码中有效,但为什么后增量运算符不起作用? [英] Why does post increment operator not work although preincrement does work in this code?
问题描述
我真的是编程新手(我是一名电子和通信工程师),我无法弄清楚为什么一个程序有效而另一个程序无效.
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.
我知道x ++和--x之间的区别.但是在这个程序的上下文中,我认为这两个程序应该以相同的方式运行.但是他们没有.
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*/
谢谢!
附言:如果这是一个琐碎或愚蠢的问题,请原谅我,但我坚持这个问题,我认为这是我可以寻求帮助的最佳地方.
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.
推荐答案
void rec(int x) {
if (x>0)
rec(x--);
printf("%d",x);
}
这将永远递归(或者至少直到耗尽堆栈空间为止). x--
表示使用x
的 current 值,然后然后减小它.
This will recurse forever (or at least until you exhaust your stack space). x--
means use the current value of x
and then decrement it.
换句话说,让我们使用参数20调用rec
.该参数大于零,因此它将依次使用当前值20 then 减量x
再次调用rec
. (但实际上是在之后调用返回.
In other words, let's call rec
with the parameter 20. That's greater than zero, so it will in turn call rec
again with the current value of 20 then decrement x
(but effectively after the call returns.
因此,您将永远用值20调用rec
,这就是为什么要耗尽堆栈的原因.
Hence you're forever calling rec
with the value of 20, which is why you're blowing out your stack.
如果将x--
更改为--x
,则会将x
递减,然后再将其传递给函数,因此它将变为20, 19, 18, ... 1, 0
,这时它将重新运行堆叠打印所有这些值.
If you change x--
to --x
, it decrements x
before passing it to the function, hence it will go 20, 19, 18, ... 1, 0
, at which point it will run back up the stack printing all those values.
如果在if
语句之前放置了printf ("before: %d\n", x)
,您将看到很多20
行输出到屏幕上.
If you had put a printf ("before: %d\n", x)
before the if
statement, you would have seen a lot of 20
lines output to the screen.
这篇关于尽管预增量在此代码中有效,但为什么后增量运算符不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!