3

In an old codebase, I found the following snippet:

for(;;){
  // code that manipulates a vector 'vec'
  if(vec.empty()) break;
}

Is there any purpose or convention behind using for(;;) instead of while(true), except for personal taste of the respective author?

Michael
  • 7,407
  • 8
  • 41
  • 84

2 Answers2

9

Older C++ compilers would not issue a warning for for(;;) but they would for while(true). Ditto for C, but with while(1).

Thus the convention stuck.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • 1
    Interesting - presumably some "condition always evaluates to true" warning "inherited" from more complex expressions and not given a special case in the way that a totally empty condition (permissible only for a `for`) apparently was. – Lightness Races in Orbit Nov 21 '18 at 13:51
  • 1
    I'm not sure what should constitute a bug fix for such a compiler – StoryTeller - Unslander Monica Nov 21 '18 at 13:51
  • 1
    This is a good historical perspective. If you add that the statements are semantically equivalent, QoI aside, I'll just delete my answer as redundant – Lightness Races in Orbit Nov 21 '18 at 13:51
  • According to the accepted answer linked by Hans Passant in comments, the reason `for(;;)` is legal code is that the empty second expression is replaced by a nonzero constant. Presumably the compiler that makes that replacement assumes that it is intentional on the part of the programmer, which is why no diagnostic is issued. – Tim Randall Nov 21 '18 at 14:02
  • @TimRandall: Methinks it's simpler than that: the "expressions" in the `for` loop (or whatever they are called these days), can be optionally present or absent leading to 8 different possibilities. Deciding on which combinations would yield warnings would have been tedious, particularly in the old days. – Bathsheba Nov 21 '18 at 14:05
  • @Bathsheba could be. I can't see a significant difference between these theories, at this point in time. – Tim Randall Nov 21 '18 at 14:08
3

No.

It is personal taste only.

It is entirely equivalent to a while (true).

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055