C/C++ Arena

Step 5 of 6

The ternary operator

The ternary operator condition ? a : b is a compact if/else that produces a value: a if the condition is true, b otherwise. Because it's an expression, you can use it right inside an assignment or a printf argument, where an if statement can't go.

#include <stdio.h>

int main(void) {
    int x = 7, y = 12;
    int bigger = (x > y) ? x : y;
    printf("bigger: %d\n", bigger);
    int items = 3;
    printf("%d %s\n", items, items == 1 ? "item" : "items");
    return 0;
}
bigger: 12
3 items

It reads like a question: "is x > y? if so x, else y".

%s and strings

The second example prints a word with %s, the format specifier for strings (text). "item" and "items" are both strings, so whichever one the ternary picks is printed. You'll learn more about strings in their own module.

When to use it

Use the ternary for small, simple choices between two values. For anything with side effects or longer logic, a normal if/else is easier to read. Nesting ternaries (a ? b : c ? d : e) is legal but quickly becomes hard to follow.

Your turn: read an int n and print n kill or n kills with the correct plural (1 is singular, everything else plural).

Previous: switch Next: Challenge: leap years