为什么这个节目不是无限跑? [英] Why does this program not run infinitely?
问题描述
应该不是这个程序无限运行,因为主要是被称为每次?以及为什么它的输出为 0 0 0 0
?我知道这是一个noob问题,但我不能得到它。什么 - 我
做的,什么是我声明为静态的效果?
INT的main()
{
静态INT I = 5;
如果我){
主要();
的printf(%D,我);
}
}
- 的
静态INT
不是每次都重新初始化。因此,每个时间主要()被调用时,i是一个下。 - 在
( - I)。
为零,递归循环终止
因此,开始了与 I = 5
,并调用一个新的副本。这其中有 I = 4
,它再次调用一个新的副本。这样继续下去,直到 I = 0
,此时函数只是终止。然后控制流程返回到调用堆栈,以及主
打印 I
,每个副本现在是0 4副本意味着4零。
Shouldn't this program run infinitely because main is being called every time? And why it's output is 0 0 0 0
? I know it's a noob question but I am not able to get it. What --i
do and what is the effect of declaring i as static?
int main()
{
static int i=5;
if(--i){
main();
printf("%d ",i);
}
}
- The
static int
is not reinitialized each time. Thus, each time main() is called, i is one lower. - when
(--i)
is zero, the recursive loop terminates.
Thus, it starts off with i=5
, and calls a new copy. This one has i=4
, which again calls a new copy. This continues until i=0
, at which point the function just terminates. Control flow is then returned up the call stack, and each copy of main
prints i
, which is now 0. 4 copies means 4 zeroes.
这篇关于为什么这个节目不是无限跑?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!