The C Language

the conditional (ternary) operator

Sometimes you want to choose between two values based on a yes/no question, all in a single small expression — 'use this if the test passes, otherwise use that'. The conditional operator, written with a question mark and a colon, does exactly this. It is called ternary because it is the one C operator that takes three parts: a test, a value-if-true, and a value-if-false.

The form is condition ? value_if_true : value_if_false. C evaluates the condition first; if it is non-zero (true) the whole expression becomes value_if_true and the other arm is not evaluated; if it is zero (false) the expression becomes value_if_false and the true arm is skipped. So 'int max = (a > b) ? a : b;' reads as: if a is greater than b, max is a, otherwise max is b. Because it is an expression that produces a value, you can drop it right inside a larger expression or an assignment, where a full if statement would not fit.

Why it matters: the ternary keeps short either-or choices compact and avoids a four-line if/else just to pick one of two values. The honest caveat is restraint: nesting ternaries inside ternaries quickly becomes unreadable, and when the two branches do work (not just pick a value), a plain if statement is clearer. Use it for simple value selection, reach for if/else when there is real logic in each branch.

int a = 7, b = 4; int max = (a > b) ? a : b; /* max becomes 7 */ printf("%d apple%s\n", n, (n == 1) ? "" : "s");

The ternary picks one of two values inline. Only the chosen arm is evaluated, so the unselected side never runs.

Only the selected branch is evaluated, so side effects in the unchosen arm never happen. Deeply nested ternaries hurt readability — prefer if/else when each branch does real work, not just selects a value.

Also called
ternary operator?:三元運算子問號冒號運算子