Purpose of while(1); statement in C

前端 未结 12 1648
终归单人心
终归单人心 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 01:06

    As others have said, it's just an infinite loop that does nothing, completely analogous to

    while (1) {
        /* Do nothing */
    }
    

    The loop with the semicolon does have a body. When used as a statement, a single semicolon is a null statement, and the loop body consists of that null statement.

    For readability, to make it plain to the reader that the null statement is the body of the loop, I recommend writing it on a separate line:

    while (1)
        ;
    

    Otherwise it is easy to miss it at the end of the "while" line, where there usually isn't a semicolon, and the reader can mistake the next line as the body of the loop.

    Or use an empty compound statement instead.

提交回复
热议问题