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: - 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.
- 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!)
- 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.
No comments:
Post a Comment