Purpose of while(1); statement in C

前端 未结 12 1625
终归单人心
终归单人心 2020-12-08 00:53

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

12条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-08 00:59

    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()).

提交回复
热议问题