Skip to content
FollowtheDamnCode

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.

Predict: the ternary in printf
#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 apples

Run 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.

Try it: absolute value
#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| = 7

Run 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: a if the condition is true, else b. "Ternary" because it takes three parts.
  • Expression — Anything that produces a value, like a + b or x > 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?