Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!uflorida!haven!aplcen!bink From: bink@aplcen.apl.jhu.edu (Ubben Greg) Newsgroups: comp.lang.c Subject: Re: comma operator: keep away? Summary: Don't misuse the for(;;) expressions Message-ID: <1104@aplcen.apl.jhu.edu> Date: 24 Apr 89 01:08:48 GMT References: <19913@iuvax.cs.indiana.edu> <10092@smoke.BRL.MIL> <19926@iuvax.cs.indiana.edu> <2179@pur-phy> Reply-To: bink@aplcen.apl.jhu.edu (Greg Ubben) Distribution: usa Organization: The Johns Hopkins University, Baltimore MD Lines: 26 In article <2179@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@aplcen.apl.jhu.edu