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 {}
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 {}
yes,
for(;;){}
is an infinite loop
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;
}
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.
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.