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

I ask this question only for the sake of knowledge (because I think it has nothing to do with a newbie like me). I read that C programmers prefer

for(; ;) {....} 

over

  while(1) {....} 

for an infinite loop for efficiency reasons. Is it true that one cycle form is more efficient than another, or is it just a matter of style?

+4
source share
1 answer

Both constructs are equivalent to behavior.

Regarding preferences:

C programming language, Kernigan and Richie,

uses form

 for (;;) 

for an infinite loop.

Programming Practice, Kernigan and Pike,

also prefers

for (;;)

"For an infinite loop, we prefer for (;;), but while (1) is also popular. Do not use anything other than these forms."

PC-Lint

also prefers

for (;;) :

716 while (1) ... - A form construct is found, while (1) .... Considering that this is a constant in a context that expects a logical one, this may reflect programming in which infinite loops are prefixed with this construct . Therefore, it is assigned a separate number and placed in the information category. A more conditional form of an infinite loop prefix for (;;)

One of the rationales (maybe not the most important thing, I don’t know) that historically for (;;) was preferable to while (1) , is that some old compilers will generate a test for the while (1) construct.

Other reasons are: for(;;) - the shortest form (number of characters), and for(;;) does not contain a magic number (as indicated by @KerrekSB in the comments to the OP).

+6
source

Source: https://habr.com/ru/post/1488996/


All Articles