I see the different conventions used in many books I had read, where you would create infinite loops with either loop structure such as:
while()
foo();
for(;;)
foo();
But really, what are the differences I should know about? which one is better?
The loops are used to repeatedly execute the instructions till the condition is true. The difference between for loop and while loop is that For is an entry controlled loop whereas while is an exit controlled loop.
Infinite while loop refers to a while loop where the while condition never becomes false. When a condition never becomes false, the program enters the loop and keeps repeating that same block of code over and over again, and the loop never ends.
A for loop is only another syntax for a while loop. Everything which is possible with one of them is also possible with the other one. Any for loop where the termination condition can never be met will be infinite: for($i = 0; $i > -1; $i++) { ... }
Loops are control structures used to repeat a given section of code a certain number of times or until a particular condition is met. Visual Basic has three main types of loops: for.. next loops, do loops and while loops.
They're semantically the equivalent. (x;y;z) { foo; }
is equivalent to x; while (y) { foo; z; }
. They're not exactly equivalent in further versions of the standard, in the example of for (int x = 0; y; z)
, the scope of x
is the for block and is out of scope after the loop ends, whereas with int x; while (y) x
it's still in scope after the loop ends.
Another difference is that for
interprets missing y
as TRUE, whereas while
must be supplied with an expression. for (;;) { foo; }
is fine, but while() { foo; }
isn not.
Here is one small difference I saw with the VS2010 disassembly in debug mode. Not sure, if it is sufficient enough to count as a significant and universally true difference (across all compiler and with all optimizations).
So conceptually these loops are same, but at a processor level, with infinite message loops, the clock cycles for the additional/different instructions could be different and make some difference.
while(1)
004113DE mov eax,1 **// This is the difference**
004113E3 test eax,eax **// This is the difference**
004113E5 je main+2Eh (4113EEh)
f();
004113E7 call f (4110DCh)
004113EC jmp main+1Eh (4113DEh) **// This is the difference**
for(;;)
f();
004113EE call f (4110DCh)
004113F3 jmp main+2Eh (4113EEh) **// This is the difference**
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With