C Tutorial
C Ternary Operator
condition ? a : b picks one of two values without a full if.
One expression, two outcomes
The ternary operator is written condition ? a : b. C evaluates the condition. If it is true (non-zero), the whole expression becomes a. If it is false (zero), the expression becomesb. You get one value. You do not get a block of statements.
That is the difference from if. An if chooses which code runs. A ternary chooses whichvalue to use. Put it on the right of an assignment, inside printf, or as a return value.
Example
#include <stdio.h>
int main(void) {
int n = 8;
const char *kind = (n % 2 == 0) ? "even" : "odd";
printf("%d is %s\n", n, kind);
return 0;
}Compile this in /c/try. That is gcc. Changen to 7 and run it again. The same line still picks a label; only the condition changed.
Same choice as a short if/else
This program is equivalent to an if with an else that each assign one pointer. The ternary version keeps the decision next to the variable. Use it when both arms are short and both produce the same kind of value.
Example
#include <stdio.h>
int main(void) {
int score = 72;
const char *result = (score >= 50) ? "pass" : "fail";
printf("%s\n", result);
return 0;
}Parentheses around the condition are not always required, but they make the test easy to see. This tutorial keeps them. The colon is not optional: every ? has a matching :.
Use it where a value is needed
Because the ternary is an expression, you can print it directly. You do not have to store it first. This program prints the larger of two integers. Swap the numbers and compile again.
Example
#include <stdio.h>
int main(void) {
int a = 9;
int b = 14;
printf("larger: %d\n", (a > b) ? a : b);
return 0;
}Extra parentheses around the ternary keep the arguments to printf easy to read. When the operator sits inside a larger expression, wrap it.
Both arms need a common type
a and b must make sense as one type. Two int values are fine. Two string literals (type const char *) are fine. Mixing "yes" with the integer1 is not a value the compiler can pick cleanly. Match the arms.
| Condition | If true | If false |
|---|---|---|
n % 2 == 0 | "even" | "odd" |
score >= 50 | "pass" | "fail" |
a > b | a | b |
The condition itself is a scalar test: comparison, !, &&, ||. Do not write if inside the parentheses. The test is an expression, the same kind you already use in an if header.
Nesting is legal, not kind
You can put a ternary in an arm of another ternary. The compiler accepts it. A person reading the line has to count question marks. Prefer else if once you have three or more outcomes.
Example
#include <stdio.h>
int main(void) {
int score = 82;
const char *grade = (score >= 90) ? "A" : (score >= 80) ? "B" : "C";
printf("%s\n", grade);
return 0;
}This compiles. The if/else chain from the If Else chapter is easier to extend. Use a nested ternary only when both extra arms stay tiny.
It is not a block
Each arm is one expression. You cannot put two statements in an arm, and you should not hide aprintf plus an assignment in one ternary. If the true path needs two lines, write anif. Stay with if when you need braces { }, more than one statement, or a chain of ranges. Next: nested loops, where one for is not enough to walk a table.
Worked examples
The short listings above are there so you can see the grammar. The programs here use the same statements on quantities that already have units: a speed, a pH, a count of bases. They are classroom numbers. Air resistance is ignored. g is 9.81 m/s² unless a line says otherwise.
Open them in the C editor at /c/try. Change one measurement and check whether the result still has the right unit.
Physics
A current limit
A fuse or a software trip might allow 0.50 A. 0.47 A is within that. The ternary picks a word. For two outcomes it is readable. For three, use if/else.
Example
#include <stdio.h>
int main(void) {
double amps = 0.47;
printf("%s\n", amps < 0.5 ? "within limit" : "trip");
return 0;
}Maths
The longer side
max(a, b) is the classic ternary. A 6 by 9 rectangle has longer edge 9. Geometry code uses this when a bounding box needs the larger extent.
max(a, b) = a > b ? a : b
Example
#include <stdio.h>
int main(void) {
double a = 6.0;
double b = 9.0;
double longer = a > b ? a : b;
printf("longer = %.0f\n", longer);
return 0;
}