haccks
haccks

Reputation: 106012

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?

Upvotes: 5

Views: 732

Answers (2)

newton-342
newton-342

Reputation: 13

Another style to consider:

while (true) {
    /* ... */
}

You will have to include stdbool.h though, which was added in C99.

Note that while (1) and while (true) are equivalent, but the latter looks more modern and will generally be more readable for people who aren't as familiar with the C language.

Upvotes: 0

ouah
ouah

Reputation: 145829

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

Upvotes: 8

Related Questions