comma operator

michael.p.lindner mpl at cbnewsl.ATT.COM
Tue Aug 1 23:18:44 AEST 1989


In article <918 at helios.toronto.edu>, dooley at helios.toronto.edu (Kevin Dooley) writes:
> In article <1989Jul28.174033.12734 at jarvis.csri.toronto.edu> flaps at dgp.toronto.edu (Alan J Rosenthal) writes:
> >dandb at k.gp.cs.cmu.edu (Dean Rubine) writes:
> >>I also occasionally use the comma to save braces:
> >Funny, I use braces to save commas:
> 
> Can anybody tell me if there is a usage where the comma is 'better'.
> By this I mean are there any places where using a comma makes the 
> code more readable, efficient, produce cleaner/faster assembler (I
> know this is compiler dependant).  It's just that I've never seen a
> program with the comma operator where I didn't scream and edit it out.
> Am I being hopelessly pedestrian here?
> 
>  Kevin Dooley         UUCP - {uunet,pyramid}!utai!helios.physics!dooley

There are only 2 uses of the comma operator which I find acceptable.

1) In a #define, where it is necessary to use multiple expressions:
	#define fatal(E)		(error(E), exit(1))
   I would NEVER NEVER NEVER #define a function macro which was not a
   single, well behaved (ie. parenthesized) expression.  As I understand
   it, this was the primary reason for the origination of the comma operator.

2) In the "modify" part of a for loop:
	for (i = 0; i < 8; j >>=1, i++)
   The reason for this is so within the loop, one can continue without
   skipping the modify of j.

In both these cases, the comma operator contributes to the "maintain-ability"
of the code, by allowing one to write a useful construct which does not
place hidden (non-obvious) restrictions on other parts of the code:
For instance:
	#define fatal(E)		{ error(E); exit(1); }

	x = (y ? z / y : fatal("division by zero"));

or
	for (i = 0; i < 8; i++) {
		if (j & 1)
			continue;
		func();
		j >>= 1;
	}

Both these examples croak, one at compile time, one at run time.

Mike Lindner
attunix!mpl
AT&T Bell Laboratories
190 River Rd.
Summit, NJ 07901



More information about the Comp.lang.c mailing list