The Ternary Operator
The ternary conditional operator
?: is the only operator in C that takes three operands, hence the name. Its syntax is condition ? valueIfTrue : valueIfFalse, and it evaluates to one of the two values depending on whether the condition is truthy. It is a compact alternative to a simple if/else when both branches just produce a value.C
#include <stdio.h>
int main(void) {
int age = 20;
const char *category = (age >= 18) ? "adult" : "minor";
printf("%s\n", category); // adult
return 0;
}Ternary as a Compact if / else
The two snippets below are equivalent. The ternary form is shorter and, when used for a simple value selection, often reads more clearly than the multi-line
if/else version.C
int a = 7, max;
/* Using if / else */
if (a > 0) {
max = a;
} else {
max = -a;
}
/* Using the ternary operator */
max = (a > 0) ? a : -a;Practical Example: Maximum of Two Numbers
C
#include <stdio.h>
int main(void) {
int a = 15, b = 42;
int max = (a > b) ? a : b;
printf("The larger value is %d\n", max);
return 0;
}Avoid Overusing or Nesting Ternaries
Nested ternaries hurt readability fast
A single, simple ternary is often clearer than an
if/else. But nesting ternaries inside each other to express multiple conditions quickly becomes hard to read and easy to get wrong, since the operator is right-associative and the visual structure does not make the branching obvious. If you need more than one condition, prefer a regular if/else if chain or a switch.C
/* Hard to read at a glance — avoid this style */
int grade = 82;
char letter = (grade >= 90) ? 'A' : (grade >= 80) ? 'B' : (grade >= 70) ? 'C' : 'F';
/* Clearer as a regular if / else if chain */
char letterClear;
if (grade >= 90) {
letterClear = 'A';
} else if (grade >= 80) {
letterClear = 'B';
} else if (grade >= 70) {
letterClear = 'C';
} else {
letterClear = 'F';
}condition ? a : bevaluates toaif condition is truthy, otherwisebGreat for short, single-value decisions; use
if/elsefor anything with side effects or multiple statementsAvoid nesting ternaries — it reads poorly and hides the actual branching logic