Search code examples
cloopsinfinite-loop

Preference of "for(; ;)" over "while(1)"


I am asking this question only for the sake of knowledge(because i think it has nothing to do with beginner like me).
I read that C-programmers prefer

 for(; ;) {....}

over

 while(1) {....}

for infinite loop for reasons of efficiency. Is it true that one form of loop is more efficient than the other, or is it simply a matter of style?


Solution

  • Both constructs are equivalent in behavior.

    Regarding preferences:

    The C Programming Language, Kernighan & Ritchie,

    uses the form

    for (;;)
    

    for an infinite loop.

    The Practice of Programming, Kernighan & Pike,

    also prefers

    for (;;)

    "For a infinite loop, we prefer for(;;) but while(1) is also popular. Don't use anything other than these forms."

    PC-Lint

    also prefers

    for (;;):

    716 while(1) ... -- A construct of the form while(1) ... was found. Whereas this represents a constant in a context expecting a Boolean, it may reflect a programming policy whereby infinite loops are prefixed with this construct. Hence it is given a separate number and has been placed in the informational category. The more conventional form of infinite loop prefix is for(;;)

    One of the rationale (maybe not the most important, I don't know) that historically for (;;) was preferred over while (1) is that some old compilers would generate a test for the while (1) construct.

    Another reasons are: for(;;) is the shortest form (in number of characters) and also for(;;) does not contain any magic number (as pointed out by @KerrekSB in OP question comments).