What for (;;) and while(); mean in C [duplicate]

我怕爱的太早我们不能终老 提交于 2019-12-01 07:24:43

问题


I am looking at some example codes and I saw someone did this

for (;;) {
// ...
}

Is that equivalent to while(1) { } ?

And what does while(condition); do? I don't get the reason behind putting ';' instead of {}


回答1:


yes,

for(;;){}

is an infinite loop




回答2:


And what does while(condition); do? I don't get the reason behind putting ';' instead of {}

Well, your question is what happens if you put or you do not put a semicolon after that while condition? The computer identifies the semicolon as an empty statement.

Try this:

#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;
}



回答3:


while just loops though a single statement until the condition is false. It doesn't have to be a compound statement (this thing: {}), it can be any statement. ; is a statement that does nothing.

while(getchar() != '\n');

will loop until you hit enter, for example. Though, this is bad practice since it will hog the thread; adding a call to a sleep method in the loop is better.




回答4:


for(;;) and while(1) are both infinite loops, and compile to the same opcodes:

L2:
    jmp     L2

Which means there is no speed difference, as the disassembly is exactly the same.



来源:https://stackoverflow.com/questions/32019724/what-for-and-while-mean-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!