什么(;;)和while(); 在C中的意思

PTN*_*PTN 3 c for-loop while-loop

我正在看一些示例代码,我看到有人这样做了

for (;;) {
// ...
}
Run Code Online (Sandbox Code Playgroud)

这相当于while(1) { }

那怎么while(condition);办?我不知道背后的原因';'而不是{}

ore*_*isf 8

是,

for(;;){}
Run Code Online (Sandbox Code Playgroud)

是一个无限循环

  • 请注意,此循环[导致未定义的行为](http://stackoverflow.com/questions/2178115/are-compilers-allowed-to-eliminate-infinite-loops/)在C11中.(在C99中,不清楚它是否确实如此).`while(1){}`不会导致未定义的行为,所以这两个循环结构是不一样的. (2认同)

Mic*_*chi 8

而什么(条件); 做?我没有理由把';'放在后面 代替 {}

好吧,你的问题是,如果你放了或者你没有在那之后放一个分号,会发生什么?计算机将分号标识为空语句.

试试这个:

#include<stdio.h>

int main(void){
    int a = 5, b = 10;

    if (a < b){
        printf("True");
    }


    while (a < b); /* infinite loop */
        printf("This print will never execute\n");

    return 0;
}
Run Code Online (Sandbox Code Playgroud)