The Ternary Operator
A one-line if-else.
3 minute read
Big idea
The ternary operator ? : picks one of two values in a single expression — a one-line if/else.
The idea
condition ? value_if_true : value_if_false
These two do the same thing:
int bigger;
if (a > b) {
bigger = a;
} else {
bigger = b;
}
int bigger = (a > b) ? a : b;
The ternary gives back a value, so you can use it anywhere a value fits — in an assignment, in printf, even inside another expression.
#include <stdio.h>
int main(void) {
int apples = 1;
printf("%d apple%s\n", apples, apples == 1 ? "" : "s");
apples = 4;
printf("%d apple%s\n", apples, apples == 1 ? "" : "s");
return 0;
}What does it print? Show the answer
1 apple
4 applesRun and edit it in the app.
%s prints text (a string) — here, either nothing or "s".
When to use it
Use the ternary for choosing a value. Use if/else for doing things — running several statements, printing in each branch, or anything that needs more than one line. Nesting ternaries (a ? b : c ? d : e) works but quickly gets hard to read — reach for else if instead.
#include <stdio.h>
int main(void) {
int x = -7;
int abs_x = x < 0 ? -x : x;
printf("|%d| = %d\n", x, abs_x);
return 0;
}output
|-7| = 7Run and edit it in the app.
Watch it
Think of it like
Asking a friend "Tea or coffee?" and getting a one-word answer, instead of a whole speech.
🕷️ Spidey-sense:
suit = night ? "black" : "red";— one line, decided, out the window.
Key terms
- Ternary operator —
condition ? a : b:aif the condition is true, elseb. "Ternary" because it takes three parts. - Expression — Anything that produces a value, like
a + borx > 0 ? x : -x.
Check yourself
What does x > 0 ? 1 : -1 give when x is -3?
The ternary operator produces…
When is if / else a better choice?