comma operator: keep away?

T. William Wells bill at twwells.uucp
Wed Apr 19 14:19:27 AEST 1989


In article <28831 at ucbvax.BERKELEY.EDU> jas at ernie.Berkeley.EDU (Jim Shankland) writes:
: I still suggest that a C programmer who understands:
:
: (A)   if (x->in_use)
:       {
:               x++;
:               y++;
:       }
:
: but who is mystified by:
:
: (B)   if (x->in_use)
:               x++, y++;
:
: had best be investigating alternate career paths.

The thing that is wrong with the latter has little to do with
mystification. What is wrong is that, for rapid and accurate
understanding of code, one should avoid appearing to do more than one
thing at a time.

In other words, the physical layout of the code should make each thing
being done appear distinct from all the other things being done.

How often have you been burned by missing the second part of a comma
operator? How frequently have you missed the assignment is some
idiocy like:

	foo(<long---complicated---expression, ((bletch = 1) * glorch);

And how often have you missed the significance of an expression that
is pasted on the end of an if? As in awful code like:

		if (expression) { statement;
		statement;      /*!*/
	}

Look rapidly at the examples following the form feed.

Which one would you understand most quickly? And which one, after a
quick glance, would you believe you had understood more accurately?


	if (!(fp1 = fopen(name1, "r")) || !(fp2 = fopen(name2, "r"))) {
		error();
	}

	if (  !(fp1 = fopen(name1, "r"))
	   || !(fp2 = fopen(name2, "r"))) {
		error();
	}

The point is that the latter makes it clear that two different things
are happening. The former you have to figure this out for yourself.

The cost is in time, and if you are just skimming the code, in
immediate comprehension.

Of course, such differences are trivial in any given fragment of code,
but when carried out throughout the program, they can make the
difference between code that is easy to understand and code whose
reading feels like wading through a swamp.

---
Bill                            { uunet | novavax } !twwells!bill
(BTW, I'm may be looking for a new job sometime in the next few
months.  If you know of a good one where I can be based in South
Florida do send me e-mail.)



More information about the Comp.unix.questions mailing list