gpt4 book ai didi

c - for 和 while 循环中没有循环条件

转载 作者:太空狗 更新时间:2023-10-29 16:46:27 25 4
gpt4 key购买 nike

while(cond) // fine
for(;cond;) //fine

但是当我删除条件部分时

while() //syntax compilation error 
for(;;) //Infinite loop

这些循环是如何在内部实现的?或者,编译器(解析器)如何知道 while 中的空条件是错误的,而 for 中的空条件是无限的?

我没有发现任何关于这个的特别的东西,我想像我这样的人(初学者)在 C 中可能有同样的困惑

最佳答案

标准要求for循环省略的条件用非零常量代替:

来自C11 6.8.5.3:(强调我的)

6.8.5.3 The for statement

1 The statement for ( clause-1 ; expression-2 ; expression-3 ) statement behaves as follows: 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. If clause-1 is a declaration, the scope of any variables it declares is the remainder of the declaration and the entire loop, including the other two expressions; it is reached in the order of execution before the first evaluation of the controlling expression. If clause-1 is an expression, it is evaluated as a void expression before the first evaluation of the controlling expression.134)

2 Both clause-1 and expression-3 can be omitted. An omitted expression-2 is replaced by a nonzero constant.

因为while循环没有这样的要求(如果条件被省略),我相信,它留给编译器实现。

关于c - for 和 while 循环中没有循环条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13146830/

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