What for (;;) and while(); mean in C
Solution 1
yes,
for(;;){}
is an infinite loop
Solution 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;
}
Solution 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.
PTN
Updated on July 09, 2022Comments
-
PTN almost 2 years
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{}
-
Dmitri over 8 yearsRight, the empty statement from the semicolon is the loop body. But sometimes that's intentional if the work is done in the condition.
-
M.M over 8 yearsNote that this loop causes undefined behaviour in C11. (In C99 it was unclear whether or not it did).
while(1) {}
does not cause undefined behaviour, so those two loop constructs are not the same. -
M.M over 8 yearsThe print may execute because
while (a < b);
causes undefined behaviour. See here for further discussion