Path: csiph.com!eternal-september.org!feeder.eternal-september.org!reader01.eternal-september.org!.POSTED!not-for-mail
From: Tim Rentsch
Newsgroups: comp.lang.c
Subject: Re: Comma operator in for() statements
Date: Fri, 27 Mar 2020 08:02:26 -0700
Organization: A noiseless patient Spider
Lines: 36
Message-ID: <86mu8196yl.fsf@linuxsc.com>
References:
Mime-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Injection-Info: reader02.eternal-september.org; posting-host="02cbe0882c270f81c5b8b4aa13e82222"; logging-data="10791"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/c7lIpcdiDdSdsQsWlV0rnZHVic1DXCdw="
User-Agent: Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux)
Cancel-Lock: sha1:ZaADZm4N6B+mO7Z2TxftYDJFBos= sha1:Bda+x/0XAx8CRTUhOxnkhn/OxoE=
Xref: csiph.com comp.lang.c:150861
Geoff writes:
> I'm aware of the hazards of using the comma operator in the tested
> expression but I ran across this example and I think it should be
> refactored, but how?
>
> for (count = 0, ent = master; ent; ent = ent->chain, count++)
> ;
I will offer a different view here. There is nothing wrong with
using the comma operator in for-expressions. Indeed it is uses
in for-expressions that provides what may be the clearest case
in favor of using the comma operator.
The problem here, if there is a problem, is the "count++" in
the third for-expression. Logically the 'count++' operation
seems like a better fit for the loop body:
for (count = 0, ent = master; ent; ent = ent->chain) count++;
I'm sure some people would prefer the 'count = 0' to be put as a
separate statement, before the for() loop. Personally I think it
makes more sense to include it in the first for-expression, because
it is part of establishing the invariant for the loop. Probably
this boils down to how one conceptualizes C's for() statement.
Some people think of for() in C as a slightly more general form
of a FORTRAN DO-loop. My view, which I think also reflects the
views of C's original authors, is for() in C offers a generalized
looping structure, with loop initialization, loop prelude, and
loop advancement sections. That perspective suggests it is
better to put 'count = 0' in the first for-expression than as a
separate statement before the for() statement. I realize other
people sometimes view it differently, and I think I understand
their reasons for the preference they have. I just don't think
either view is "right" is some absolute sense, only a reflection
of how one conceptualizes C's for() construct.