The Conditional Operator
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.
The shortcut
Read ? as "then" and : as "otherwise". "t less than 100, then cold, otherwise t less than 250, then mild, otherwise hot."
First test
t < 100: 180 is not less than 100, so skip"cold"and go to "otherwise".
When should you not use it? When a branch needs to do something, such as switching the heater on and logging it, or when the nesting grows beyond two levels. The conditional operator chooses values; if/else runs statements.
Drills
Answer fast — trust the rule.
After int x = 7; int y = x % 2 == 0 ? 10 : 20;, what is y?
With the label expression from this lesson, what does a reading of t = 260 give?
What is the type of n > 0 ? 1 : 0.5?
After int calls = 0; int r = 1 ? 5 : (calls = 1);, what is calls?
Remember
- cond ? yes : no is an if/else that hands back a value, and only one branch runs.
- Shortcut: read
?as "then" and:as "otherwise"; nesting chains to the right. - Trap: low precedence (use parentheses) and a single common result type.
