为什么输出是0000和如何? [英] Why Output is 0000 and How?
问题描述
我执行这个程序,我无法理解为什么输出为0的四倍。任何人可以帮助我理解它是如何工作的?我不明白为什么printf来执行,当条件不满足,为什么它执行四次。
INT的main()
{
静态INT I = 5;
如果我)
{
主要();
的printf(%D,我);
}
}
您主要功能打印4次0,因为printf语句发生后递归调用和 I
是一个静态变量。静态变量被初始化只有一次,它不被破坏的功能终止后,因为它不分配到函数栈。结果
作为结果,价值我在
的printf
始终为0为 I 使用
code>是每次递减主
被调用,第一个的printf
函数是最深的函数后执行返回,因为 I = 0
。
要更好地理解这一解决方案,让我们来看看堆栈调用:
main()的I = 5(第一次调用)
如果(4)//真
main()的(第二个电话)
如果(3)//真
main()的(第三个电话)
如果(2)//真
main()的(第四调用)
如果(1)//真
main()中(第五轮)
如果(0)//假尾递归无打印,因为条件为假
返回
打印(一)// 0(第四呼叫)
打印(一)// 0(第三个电话)
的printf(我)// 0(二调用)
打印(一)// 0(第一次调用)
的主
被称为5次,但在应用程序打印4个零,因为最后一次通话不打印任何东西作为如果
的条件是假的。
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.
这篇关于为什么输出是0000和如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!