The Conditional Operator
The conditional operator cond ? a : b is an expression that evaluates the condition and then only one of its two branches, producing a value that can be assigned or passed on directly.
Choose one result from a condition while keeping the expression's type visible.
The logger's status line says "Heater ON" or "Heater OFF". Writing a full if/else with two nearly identical printf calls feels heavy for choosing one word. C has an operator for exactly this: pick one of two values, right inside an expression.
The rule
cond ? yes : no — an if/else that hands back a value.
The conditional operator (often called the ternary operator, because it takes three operands) works like this:
- Evaluate the condition.
- If it is nonzero (true), evaluate the second operand, and that is the result.
- Otherwise, evaluate the third operand, and that is the result.
Only one of the two branches is ever evaluated.
printf("Heater %s\n", heater_on ? "ON" : "OFF");
int warmest = a > b ? a : b;
const char *label = t < 100 ? "cold"
: t < 250 ? "mild"
: "hot";Because it is an expression, it can go where statements cannot: inside a function argument, in an initializer, in a return.
Things to know:
- It nests from the right.
x ? a : y ? b : cmeansx ? a : (y ? b : c), which gives the neat "else if" chain inlabelabove. - Its precedence is very low, just above assignment and the comma. Inside a longer expression, wrap the whole conditional in parentheses:
total + (bonus ? 10 : 0). - The result has one type. If the branches are arithmetic types, they are converted to a common type, just like the two operands of
+. Son > 0 ? 1 : 0.5has typedoubleeven when the condition is true, and printing it with%dwould be undefined behaviour.