comma operator: keep away?
Ubben Greg
bink at aplcen.apl.jhu.edu
Mon Apr 24 11:08:48 AEST 1989
In article <2179 at pur-phy> (Sho Kuwamoto) writes:
>[...]
>As for another example where you could use the comma operator usefully,
>how about...
>
> for(i=0, p=head; p->next != NULL; i++, p=p->next)
>or something.
Right idea, but bad example. People too often cram expressions in the
for(;;) that are not related to the loop control, just to avoid a couple of
extra lines. I admit that I do it myself. In this case, the execution of
the loop is totally dependent on the contents of the linked list. It would
be more clearly written as:
i = 0;
for (p=head; p->next!=NULL; p=p->next) {
/* I normally use "p" instead of "p->next!=NULL" */
/* We're skipping the last item here. */
i++;
}
It's especially hard to resist this when the for expression would otherwise
be null. I would be tempted to hide the i=0 in its declaration and the i++
in an expression, but this is arguably also bad. Actually, I'm not all that
firm on this opinion. Comments?
-- Greg Ubben
bink at aplcen.apl.jhu.edu
More information about the Comp.lang.c
mailing list