What purpose does while(1);
serve ? I am aware while(1)
(no semicolon) loops infinitely and is similar to a spinlock situation. However I do not see where while(1);
could be used ?
if(!condition)
{
while(1);
}
Note: This is not a case of do
-while()
or plain while(1)
.
Please note that all valid statements of the language do not have to serve a purpose. They are valid per the grammar of the language.
One can build many similar "useless" statements, such as if (1);
.
I see such statements as the conjunction of a conditional (if
, while
, etc.) and the empty statement ;
(which is also a valid statement although it obviously serves no specific purpose).
That being said, I encountered while (1);
in security code. When the user does something very bad with an embedded device, it can be good to block them from trying anything else.
With while (1);
, we can unconditionally block a device until an accredited operator manually reboots it.
while(1);
can also be part of the implementation of a kernel panic, although a for(;;) {}
loop seems to be a more common way of expressing the infinite loop, and there might be a non-empty body (for instance to panic_blink()
).