Skip to the workspace
Pebellslearn by building
Operators  ›  Lesson

The Conditional Operator

Ternary 10 minThe 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.

c / The Conditional Operator

Explore each scene at your own pace.

01 · The rule

The rule

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:

  1. Evaluate the condition.
  2. If it is nonzero (true), evaluate the second operand, and that is the result.
  3. 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 : c means x ? a : (y ? b : c), which gives the neat "else if" chain in label above.
  • 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 +. So n > 0 ? 1 : 0.5 has type double even when the condition is true, and printing it with %d would be undefined behaviour.
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.