The ternary (conditional) operator in C
In C, the real utility of it is that it's an expression instead of a statement; that is, you can have it on the right-hand side (RHS) of a statement. So you can write certain things more concisely.
Some of the other answers given are great. But I am surprised that no one mentioned that it can be used to help enforce const
correctness in a compact way.
Something like this:
const int n = (x != 0) ? 10 : 20;
so basically n
is a const
whose initial value is dependent on a condition statement. The easiest alternative is to make n
not a const
, this would allow an ordinary if
to initialize it. But if you want it to be const
, it cannot be done with an ordinary if
. The best substitute you could make would be to use a helper function like this:
int f(int x) {
if(x != 0) { return 10; } else { return 20; }
}
const int n = f(x);
but the ternary if version is far more compact and arguably more readable.
The ternary operator is a syntactic and readability convenience, not a performance shortcut. People are split on the merits of it for conditionals of varying complexity, but for short conditions, it can be useful to have a one-line expression.
Moreover, since it's an expression, as Charlie Martin wrote, that means it can appear on the right-hand side of a statement in C. This is valuable for being concise.