Re: while (1) vs. for ( ;; )



Michael B Allen <mba2000@xxxxxxxxxx> writes:

> Should there be any preference between the following logically equivalent
> statements?
>
> while (1) {
>
> vs.
>
> for ( ;; ) {
>
> I suspect the answer is "no" but I'd like to know what the consensus is
> so that it doesn't blink through my mind anymore when I type it.

My experience is that there is less cognitive load if the
'while(1)' form is used. That is, when reading code, I can
read either form just fine, but something in my conscious
brain notices if the 'for(;;)' form is used, which slows
down my reading just a tiny bit. The 'while(1)' form gets
read and turned into "loop forever" without losing flow or
needing any conscious brain cycles. For these reasons --
that is, higher productivity -- I prefer the 'while(1)'
form.

I was surprised at how many people reported that a compiler
they use issues a warning for 'while(1)' and gave that as a
reason for giving preference to the 'for(;;)' form. It
seems like a choice should be made on the basis of what's a
better expression (lower defect rate, higher productivity,
better understood by the readers), not on the basis of some
errant warning message. Getting a warning on 'while(1)'
(assuming it can't be separately disabled) is a sign that
the person who wrote the warning code didn't think through
what he was doing, not that the construct is suspect. Style
choices should determine what kinds of warning messages come
out of the compiler, not the other way around.

I myself would have no problem with people writing

FOREVER {
}

assuming a suitable '#define FOREVER <...>', _provided_ the
definition had made its way into a project-level include
file and was used and recognized by the team as a whole and
not just by some individuals. Doing that might be a way of
getting team consensus and simultaneously avoiding the whole
while/for discussion altogether.
.



Relevant Pages


Loading