I found an empty for statement in an existing bit of code and I'm wondering what it does and is it "safe". It just feels wrong.
for(;;)
{
//some if statements and a case statement
}
Thanks!
This is one way of creating an infinite loop. It's a regular for
loop, but with empty initialization, condition, and increment expressions. Because the condition expression is a no-op, the loop never exits. It's perfectly "safe" assuming it has a terminating condition (a break
or return
statement [or even a goto
, I suppose]) somewhere.
Personally, I prefer to write infinite loops with while
s:
while (true)
{
//some statements and a case statement
}
(because for
is for iteration and while
is for repetition).
However, after reading this question (linked by @jailf), I now prefer while (42) { ... }
.
It's equivalent as having an infinite loop:
while (true) {
}
It's safe. You need to provide an external exit mechanism though. I.E., with a break within the for
loop.
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