What is the conditional (ternary) operator ?: in C and when is it worth using?
cond ? a : b evaluates to a if cond is true and b otherwise — it's an expression (it yields a value), unlike if/else which is a statement.
The ternary operator is the only operator in C that takes three operands, hence "ternary". It lets you fold a small if/else into a single expression, which matters because "vertical space is precious" — a compact assignment is often clearer than four lines of branching:
// Instead of:
if (a != NULL) c = *a;
else c = 0;
// Write:
c = a ? *a : 0;
Because it's an expression, it can appear anywhere a value is expected — inside a printf argument, a return, an array index, etc.:
printf("%d item%s\n", n, n == 1 ? "" : "s");
return x > 0 ? x : -x; // absolute value
Gotcha — don't nest it. Chained ternaries become unreadable fast:
// What does this even do?
c = a ? *a ? *a : b ? *b : 0 : 1;
When you'd need more than one level, reach for a plain if/else or a switch instead. The ternary is for the simple "pick one of two values" case.
Go deeper:
Ternary conditional operator — Wikipedia — the
?:operator across C-like languages.