Moin, I just found a for-loop in some source code.
for (;;) {
// some work
if (condition) {
break;
}
}
How is this for (;;)
working ?
Moin, I just found a for-loop in some source code.
for (;;) {
// some work
if (condition) {
break;
}
}
How is this for (;;)
working ?
This for(;;)
is an infinite loop.
As per C11
, chapter §6.8.5.3, The for
statement,
The statement
for
( clause-1;
expression-2;
expression-3 ) statement
behaves as follows: The expression expression-2 is the controlling expression that is evaluated before each execution of the loop body.[...]
and (emphasis mine)
Both clause-1 and expression-3 can be omitted. An omitted expression-2 is replaced by a nonzero constant.
Also, for the usage of the controlling expression
An iteration statement causes a statement called the loop body to be executed repeatedly until the controlling expression compares equal to 0. [...]
So, in case, all three are removed, the controlling expression is considered as non-zero, which is TRUE forever, thus essentially making it an infinite loop.
It's an infinite loop, like
while (1)
That was mostly used befroe because some compiler complain when they detected an infinite loop with while(1).
The three part of for is optionnal, so if the initialisation part is missing, then there is no initialization, if the test part is missing, it's assume that's true, etc.
for (;;) {
// some work
if (condition) {
break;
}
}
is equivalent to
do
{
//some work
}while(!condition);
Read this as "forever".
It repeats the block until the condition is met, and the break
statement is executed.
It is an infinite loop. It means the loop will keep execution until you use break or exit function.