The ternary operator
- C course
- Beginner
- Lesson 39/116
- 4 min
Learn to write a conditional expression in one line with ? :.
The ternary operator
With ? and : you write a conditional expression in one line. Syntax: condition ? true_value : false_value. The result is a value; you can use it in an assignment.
int a = 5, b = 9;
int max = (a > b) ? a : b;
printf("Max: %d\n", max); // 9Parentheses around the condition aren't required but improve readability. With if/else: if (a > b) max = a; else max = b;. Ternary is preferred for short expressions.
Ternary inside printf
You can use ternary directly inside printf; this concisely replaces an if/else block.
int n = 7;
printf("%s\n", (n % 2 == 0) ? "Even" : "Odd");Here %s prints the string returned by the ternary. Nested ternary is possible but hurts readability; in that case prefer if/else.
Practice Find the larger with ternary
Write a C program. Declare int a = 5; and int b = 9;. Find the larger with int max = (a > b) ? a : b;. Print with printf("Max: %d\n", max);. Put #include <stdio.h> at the top.
Starter code
#include <stdio.h>
int main(void) {
// Declare a and b, find max with ternary, print it
return 0;
}Sample solution
#include <stdio.h>
int main(void) {
int a = 5;
int b = 9;
int max = (a > b) ? a : b;
printf("Max: %d\n", max);
return 0;
}Expected output
Max: 9
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does (a > b) ? a : b return?
int a = 5, b = 9;
int max = (a > b) ? a : b;- Always a
- Always b
- Their sum
- The larger one Correct answer
Explanation: If true returns a, if false returns b; so the larger one.
2 Complete the ternary
int sign = (x >= 0) ? 1 : ____;
int sign = (x >= 0) ? 1 : -1;
Explanation: Returns -1 for negative values.
3 Match ternary and if/else
| Term | Meaning |
|---|---|
condition ? |
Condition check |
: true |
First value |
: false |
Second value |
if/else |
Blocks |