gpt4 book ai didi

c - "for(; ;)"优先于 "while(1)"

转载 作者:太空狗 更新时间:2023-10-29 15:26:51 26 4
gpt4 key购买 nike

我问这个问题只是为了了解知识(因为我认为这与我这样的初学者无关)。
我读到 C 程序员更喜欢

 for(; ;) {....}

结束

 while(1) {....}

为了效率的原因无限循环。一种形式的循环确实比另一种更有效,还是仅仅是风格问题?

最佳答案

两种结构在行为上是等价的。

关于偏好:

C 编程语言,Kernighan & Ritchie

使用表格

for (;;)

无限循环。

编程实践,Kernighan & Pike,

也喜欢

for (;;)

"For a infinite loop, we prefer for(;;) but while(1) is also popular. Don't use anything other than these forms."

PC-Lint

也喜欢

对于 (;;):

716 while(1) ... -- A construct of the form while(1) ... was found. Whereas this represents a constant in a context expecting a Boolean, it may reflect a programming policy whereby infinite loops are prefixed with this construct. Hence it is given a separate number and has been placed in the informational category. The more conventional form of infinite loop prefix is for(;;)

历史上 for (;;) 优于 while (1) 的理由之一(也许不是最重要的,我不知道)是一些旧的编译器会为 while (1) 构造生成测试。

另一个原因是:for(;;) 是最短的形式(字符数)并且 for(;;) 不包含任何魔数(Magic Number) (正如 OP 问题评论中的 @KerrekSB 所指出的那样)。

关于c - "for(; ;)"优先于 "while(1)",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17394671/

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