OT: for (;;) {} vs while (true) {}

H. S. Teoh via Digitalmars-d digitalmars-d at puremagic.com
Fri Nov 25 09:01:23 PST 2016


On Fri, Nov 25, 2016 at 03:20:24AM -0800, Jonathan M Davis via Digitalmars-d wrote:
> On Friday, November 25, 2016 12:10:44 Timon Gehr via Digitalmars-d wrote:
> > On 25.11.2016 11:33, Claude wrote:
> > > ...
> > >
> > > Between "for(;;)", "while(true)" and "do while(true)", I would use the
> > > "while (true) { }" for pure readability and semantic reasons.
> > > ...
> >
> > What semantic reasons?
> 
> Probably the complete lack of a condition to test in for(;;). I
> confess that I was shocked when I found out that it was legal to have
> a for loop without a condition. That seems like doing while() or if(),
> which makes no sense.

Sure it does. A conditionless loop is exactly what an infinite loop is.
A while-loop, by definition, has a condition (loop *while* something is
true, stop looping when it's no longer true), and an if-statement by
definition is conditional. Neither match the nature of an infinite loop,
which is infinite because it has no exit condition.

Well, OK, a loop can also be infinite if the exit condition just happens
to be always true, but I feel that is more deceptive than a
conditionless loop when it's deliberately written, since a conditional
loop whose condition happens to be always true sounds to me like a bug
or a subversion (we intend this loop to stop when condition X becomes
false, but bwahaha I arranged for X to never become false!). When a loop
is *deliberately* meant to be infinite, I see a conditionless loop as a
more faithful representation of that intent.

Therefore I prefer `for(;;)` over any of the `while(true)`, `while(1)`,
etc., variations. It conveys intent in a more straightforward, up-front
way.

If it helps you stomach it, you could interpret the `(;;)` as a funny
way of saying "ever", so in essence you're saying `for-ever { ... }`.


T

-- 
Computers shouldn't beep through the keyhole.


More information about the Digitalmars-d mailing list