A question of style

George V. Reilly gvr at brunix
Mon Dec 4 08:41:25 AEST 1989


In article <3552 at convex.UUCP> grogers at convex.COM (Geoffrey Rogers) writes:
< In article <1989Nov30.001947.14883 at aqdata.uucp> sullivan at aqdata.uucp (Michael T. Sullivan) writes:
< >From article <547 at mars.Morgan.COM>, by amull at Morgan.COM (Andrew P. Mullhaupt):
< >while (c = getchar(), c != EOF)
< >{
< >	...
< >}
< >
< >I posted this instead of mailing it to see what, if any, reaction it got.
< >I'm always interested in coding style.
< 
< In this case I would write the above as:
< 
< while ((c = getchar()) != EOF)
< {
< 	...
< }
< 
< IHMO this is much clearer then the above. In general the only places
< I have found to use the comma operator is either in for-statements,
< macros and maybe within expressions of ? : expression.

Because of the two uses of the comma as a parameter separator and as a
sequential-expression separator, you can occasionally get unexpected
results.  Consider:

#define single(list) printf list
#define double(list) printf(list)

main()
{
	single("%d %d %d", 1, 2, 3);
	double("%d %d %d", 1, 2, 3);
}

The expansion of |single()| will yield |printf("%d %d %d", 1, 2, 3)|, while
the expansion of |double()| will yield |printf(("%d %d %d", 1, 2, 3))|.
The argument to the second printf will be treated as four comma-separated
expressions which evaluate to the last expression (3), ultimately
yielding |printf(3)|, which will probably cause a segmentation fault
and a core dump.  That's what happened to me the other day, at least.

In short, while the comma operator is sometimes useful (as in the cases
indicated in the quotation above), its potential ambiguity makes it
dangerous.
------
George V. Reilly			gvr at cs.brown.edu
uunet!brunix!gvr   gvr at browncs.bitnet	Box 1910, Brown U, Prov, RI 02912



More information about the Comp.lang.c mailing list