1. A
Ternary sitting on its
nest,
incubating its eggs.
2. An annoying idiom found in
programming languages descended from
C.
The
C conditional operator (
K&R2, page 208) is not really
the ternary operator, but
a ternary operator, in that it takes three
operands. It just happens that C has only one
operator that does that. It looks like this:
a ? b : c
. . . where
a a
boolean expression, and
b and
c are
expressions that both evaluate to the same type (or at least close enough to satisfy the
compiler). If
a is nonzero, the expression returns
b; otherwise, it returns
c.
In other words,
( 0 ) ? 1 : 2 will return 2 and
( 1 ) ? 1 : 2 will return 1.
This is very handy and nifty, but there are
'leet programmers in this world who abuse the thing to write
unreadable C code. For example,
1 ? 1 ? 2 & 3 : 4 ? 5 % 6 : 7 : 8 is a
valid expression according to my
compiler. It returns 2. what exactly is it doing? Good question! It's evaluated like this:
1 ? (1 ? (2 & 3) : (4 ? (5 % 6) : 7)) : 8.
Indenting these things can clarify them even more:
( 1 )
? ( ( 1 )
? (2 & 3)
: (4 ? (5 % 6) : 7) )
: 8;
Of course, once you do that, it's not
'leet any more because it's readable by humans. It also starts looking suspiciously like
LISP, in a superficial sort of a way.