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 sta
This has been asked multiple times on SO. The best discussion on the topic is at the following link:
Is "for(;;)" faster than "while (TRUE)"? If not, why do people use it?
This is very common on embedded systems without an operating system. If your program terminates, there is no underlying system to handel that. So mostly there's one huge infinite loop in which most of the operations are handled.
It's sometimes called a "forever" loop, because that's what it does. Look for either a break;
or return;
statement inside the loop or for the loop to be wrapped in a try/catch block. Personally, I try avoid that kind of thing.
Were there any break
, return
, or throw
statements? That‘s the only way out. Is it safe? It depends if you feel safe inside an infinite loop. Some applications need one.
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.
It's valid syntax for an infinite loop. You need to "break;" out of it. This was popular back in the C++ days IIRC.
As far as being safe, you're right in feeling "wrong" about this. Usually there would be an "if" condition inside where you would decide if you continue or break the loop. If you don't verify all execution paths it could very well lead to an infinite loop. I would try and do this some other way.