section 2.11: Conditional Expressions

``Ternary'' is a ten-dollar word meaning ``having three operands.'' (It's analogous to the terms unary and binary, which refer to operators having one and two operands, respectively.) The conditional operator is a bit of a frill, and it's a bit obscure, so you may skip section 2.11 in the book on first reading, but please read the comments in these notes just below (under the mention of ``annoying compulsion'').

page 52

To see what the ?: operator has bought us, here is what the array-printing loop might look like without it:

	for(i = 0; i < n; i++) {
		printf("%6d", a[i]);
		if(i%10==9 || i==n-1)
			printf("\n");
		else	printf(" ");
	}

You may be finding this compulsion to write ``compact'' or ``concise'' code using operators like ++ and += and ?: a bit annoying. There are three things to know:

  1. In complicated code, these operators allow an economy of expression which is beneficial. Mathematicians are constantly inventing new notations, in which one letter or symbol stands for a complicated expression or operation, in order to solve complicated problems without drowning in so much verbiage that it would be impossible to follow an argument or check for errors. Computer programs are large and complex, so well-chosen abbreviations can make them easier to work with, too.
  2. Some C programmers, it's true, do take the urge to write succinct or concise code to excess, and end up with cryptic, bewildering, obfuscated, impenetrable messes. (I'm not apologizing for them: I hate overly abbreviated, impossible-to-read code, too!)
  3. Since there is overly concise C code out there, it's occasionally necessary to dissect a piece of it and figure out what it does, so you need to have enough familiarity with these operators, and with some standard, idiomatic ways in which they're commonly combined, so that you won't be utterly stymied.
However, there is nothing that says that you have to write concise code yourself. Don't be lured into thinking that you're not a ``real C programmer'' until you routinely and easily write code which no one else can read. Write in a style that's comfortable to you; don't be embarrassed if your code seems ``simple.'' (Actually, the very best code seems simple, too.) With time, you'll probably come to appreciate at least some of the idioms, and to be comfortable enough with them that you may want to use a few of them yourself, after all.


Read sequentially: prev next up top

This page by Steve Summit // Copyright 1995, 1996 // mail feedback