gpt4 book ai didi

c - c程序中的for循环混淆

转载 作者:行者123 更新时间:2023-12-04 11:17:25 24 4
gpt4 key购买 nike

为什么循环从 2 运行到 7?

int i;    
for(i=1;i<=6;printf("\n%d\n",i))
i++;

这个的输出是

2
3
4
5
6
7

但是 i 的限制是 6。

最佳答案

for 循环的语法是

for ( clause-1 ; expression-2 ; expression-3 ) statement

执行如下,引用自 C11, chapter §6.8.5.3, (emphasis mine)

The expression expression-2 is the controlling expression that is evaluated before each execution of the loop body. The expression expression-3 is evaluated as a void expression after each execution of the loop body. [....]

这里,i++ 是正文,printf("\n%d\n",i)expression-3

所以,执行的顺序是这样的

 i = 1;
start loop

i < = 6 //==> TRUE
i++; //i == 2
printf // Will print 2 ///iteration 1 done

i < = 6 //==> TRUE
i++; //i == 3
printf // Will print 3 ///iteration 2 done
.
.
.
i < = 6 //==> TRUE
i++; //i == 6
printf // Will print 6 ///iteration 5 done

i < = 6 //==> TRUE
i++; //i == 7
printf // Will print 7 ///iteration 6 done

i < = 6 ==> FALSE

end loop.

关于c - c程序中的for循环混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54439608/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com