Some good analysis already of what the conditional means. Just wanted to contribute a couple suggestions:
- consider writing or reordering such expressions such that the
?
and :
alternate,
- consider breaking them on to multiple lines with indentation reflecting their processing.
Either or both of these should make it easier to keep track of what they do.
Consider:
i < 2 ? !i ? x[i] : y : x[1] # somewhat confusing...
Just indenting to reveal processing precedence:
i < 2 // if just put ? and : beneath related condition
? !i // then if
? x[i] // then
: y // else
: x[1] // else
Or to simplify while keeping one-liner concision, try:
i >= 2 ? x[1] : !i ? x[i] : y # equivalent but simpler to "grok" (see below)
Expression ordered to alternate ?
and :
work like a simple if
/ else if
/ else if
/ else
chain, so you can process and eliminate possibilities steadily as you work your way through.
if (i >= 2)
(value is) x[1]
else if (!i)
x[i]
else
y;
I sometimes write alternating conditionals across lines too:
std::cout << (i >= 2 ? x[1] : // "if condition1 then value1 else
!i ? x[i] : // if condition2 then value2 else
y); // value3"
...or sometimes (depending on the line lengths and visual complexity) going the whole hog and lining up the :
beneath ?
...
std::cout << (i >= 2
? x[1]
: !i
? x[i]
: y);
As with many stylistic aspects of C++ source code, picking a nice layout is a bit of an art - but experimentation is a good way to get a feel for it.