I've written infinite loops like this numerous times over the years in both C and C++, but today is the first time I really thought about it -- why is it an infinite loop when the condition clause is empty? One would expect you'd have to write something like for(;true;);
to get a valid infinite loop?
while();
doesn't compile nor does while(;);
Anyways, I like the for(;;);
syntax and use it often, but is it a special case to treat an empty condition block as true or are there other cases in C or C++ where an empty condition expression is interpreted as true?
The C Standard explicitly describes this behavior of for
loops:
Both clause-1 and expression-3 can be omitted. An omitted expression-2 is replaced by a nonzero constant.
Similarly, for C++:
Either or both of the condition and the expression can be omitted. A missing condition makes the implied while clause equivalent to while(true).
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