comma operator: keep away?

Mark A Terribile mat at mole-end.UUCP
Tue Apr 25 17:39:37 AEST 1989


In article <1104 at aplcen.apl.jhu.edu>, bink at aplcen.apl.jhu.edu (Ubben Greg) writes:
> 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)


> 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.  ... the execution of the loop is totally dependent on the
> contents of the linked list.  ...

In this case, I respectfully disagree.

Since the point of the loop is to establish a relationship between the
number of items in the linked list and the value of  i , and since the
code that manipulates  i  is quite short, I prefer the ``compact'' form.
Just be sure to write the null statement as something more than an
unadorned semicolon.  I like    /* NULL */ ;   and    {}   best myself.

Even if there is something else that must be done each time around, I would
prefer to put lockstep counting in the loop control; it reduces the
likelyhood that someone who comes along later to do bodacious things to the
other code will mess up this important but hard-to-see-for-its-small-size
counting code.

Oh, and I *definately* *would* *not* put the initialization of  i  in the
declaration unless it were a nested local declaration whose scope began
right before the for(;;) and expired right after the for(;;).  Even then
I'd have some doubts.  The initialization to zero is part of establishing
that relationship between the cardinality of the linked list (if I may
express the thing that way) and the value of  i .
-- 

(This man's opinions are his own.)
>From mole-end				Mark Terribile



More information about the Comp.lang.c mailing list