Lesson 48 +10 XP

The Conditional (Ternary) Operator

The Conditional (Ternary) Operator

The ternary operator is the compact way to pick one of two values. It is a little if/else squeezed into one line.

The shape

condition ? valueIfTrue : valueIfFalse

  • First, decide on the condition.
  • If it is true, the result is valueIfTrue.
  • If it is false, the result is valueIfFalse.

Example

int time = 20;
printf("%s\n", time < 18 ? "Good day." : "Good evening.");
// Good evening.

Choosing between two values

int a = 7;
int b = 3;
int bigger = (a > b) ? a : b;   // 7

When not to use it

For longer or nested logic, a normal if/else is much easier to read. The ternary shines on short, single-value decisions only.

TL;DR

  • result = condition ? valueA : valueB.
  • If true take valueA, otherwise take valueB.
  • Great for short single-value decisions.
  • Use a normal if/else for long logic.