groundfungus:
SirNickity, you say that ternary operation "is a very concise way of picking between two (or more) options". Could you elaborate on the "or more" part. I seem to remember something like that from Fortran (maybe). Just curious.
The op itself can only choose between two options, but you can extend that by compounding statements. Here's an example that determines whether "it's still today" based on whether I've mentally changed days, regardless of wall-clock time:
uint8_t is_still_today = (have_slept)
? ((just_a_nap) ? true : false) // Still today if it was just a nap
: (up_over_24_hours) ? false : true; // No longer today if it's been an all-nighter
Here's an example that falls through conditions to return a status code based on a signed int. 0 means nothing happened, > 0 means data received, < 0 means there was a specific error, which is passed to the caller:
int getData () {
int retval = some_function();
return (retval == 0) ? ERROR_NOTHING_TO_DO
: (retval > 0) ? ERROR_DATA_RECEIVED : retval;
}
In general, compounding statements can get messy and it might be better to expand this to if/else or switch instead. However, I'll almost always choose the ternary over if/else for simple assignments. In dynamically-typed langauges like perl and PHP, it can be really handy to do things like this:
function get_preferences ($uid = NULL) {
// If the caller passed a UID, look up that user's preferences
// Otherwise, use system defaults (uid 0 in the database)
$uid = ($uid === NULL) ? 0 : intval($uid);
$q = Util::getDB()->prepare( "SELECT * from user_prefs WHERE uid = ?" );
$q->bind_param('i', $uid);
$q->execute();
return $q->fetch();
}
Even if you, as a non-ternary fan, come across this code, it's pretty evident what it does. Good comments will help make it obvious, and abuse of syntax and order of operations will make it a tangled, obfuscated mess. That's the case with just about any language construct. There's often more than one way to do it, and I'll not hesitate to use different tools (and as you can see in my examples, also different indentation and line-break styles) to help illustrate the purpose and intent, while being as efficient as possible.