Posts

Showing posts from July, 2023

The C Ternary Operator ?: is for (lisp) lovers

 The C/C++/JAVA Ternary Operator (or inline if as I like to call it): 

(test) ? do-if-true : do-if-false 

as in:

printf("x is %s than y", (x > y) ? "larger" : "smaller");

Also legal is to place the parentheses around the whole thing:

(test ? if-true : if-false)

All the hits on google start with half a page of blather before they get to a complete example like the one above. Which is probably how they get traffic, but what a waste. I'm putting the blather here where it's easy to skip!

I love this operator because of that short LISP detour I took in my 20s (after the Smalltalk detour of my teens, and before my main path of being a Matlab hacker in my 30s). Like an s-expression it allows you to do things that would otherwise require temporary variables, or lots of duplicate code. People criticize the ternary operator because it's confusing, which is fair. So is Lisp if you don't use it often (and goodness knows I haven't written Lisp in more than a decade so I can really sympathize with that one).

And yes there's a bug in my example. Consider x = y = 1; 

You could do this, however:

(x > y ? "larger" : (x == y ? "equal" : "smaller")) 

but I have to admit at that point I start to agree with the detractors that it's too hard to read. On the other hand, the equivalent if statement either has 3 printfs or a temporary variable, which isn't that great either. 

Bonus chatter:

lisp syntax (from memory, untested):

(if (> x y) "larger" (if (= y x) "equal" "smaller" ))

and the equivalent if-based solution in c:

if (x > y)
  printf("x is larger than y");
else if (x == y)
  printf("x equals y");
else
  printf("x is smaller than y");


Email me

Name

Email *

Message *