Path: utzoo!attcan!uunet!brunix!gvr From: gvr@brunix (George V. Reilly) Newsgroups: comp.lang.c Subject: Re: A question of style Summary: Commas can bite Message-ID: <22139@brunix.UUCP> Date: 3 Dec 89 21:41:25 GMT References: <547@mars.Morgan.COM> <1989Nov30.001947.14883@aqdata.uucp> <3552@convex.UUCP> Sender: news@brunix.UUCP Reply-To: gvr@panda.UUCP (George V. Reilly) Organization: Brown University Department of Computer Science Lines: 48 In article <3552@convex.UUCP> grogers@convex.COM (Geoffrey Rogers) writes: < In article <1989Nov30.001947.14883@aqdata.uucp> sullivan@aqdata.uucp (Michael T. Sullivan) writes: < >From article <547@mars.Morgan.COM>, by amull@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@cs.brown.edu uunet!brunix!gvr gvr@browncs.bitnet Box 1910, Brown U, Prov, RI 02912