C Ternary Operator
In this page:
What is the Ternary Operator?
The ternary operator condenses a simple if-else into one expression using the syntax condition ? valueIfTrue : valueIfFalse, which is especially handy when you just need to pick between two values rather than run different blocks of statements.
Example: What is the Ternary Operator?
#include <stdio.h>
int main() {
int age = 20;
char *status = (age >= 18) ? "Adult" : "Minor";
printf("%s", status);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Finding the Maximum
Finding the larger of two numbers can be written in one line as max = (a > b) ? a : b;, avoiding a full four-line if-else block for what's fundamentally a simple choice between two values.
Example: Finding the Maximum
#include <stdio.h>
int main() {
int a = 7, b = 12;
int max = (a > b) ? a : b;
printf("%d", max);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Pass or Fail Check
For binary outcomes like pass/fail, the ternary operator lets you compute a result directly: result = (score >= 50) ? "Pass" : "Fail";, keeping the logic compact and readable in a single assignment.
Example: Pass or Fail Check
#include <stdio.h>
int main() {
int score = 65;
char *result = (score >= 50) ? "Pass" : "Fail";
printf("%s", result);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Even or Odd
Combining n % 2 == 0 with the ternary operator lets you classify a number as even or odd in a single expression, such as label = (n % 2 == 0) ? "Even" : "Odd";, without a separate if statement.
Example: Even or Odd
#include <stdio.h>
int main() {
int n = 7;
char *label = (n % 2 == 0) ? "Even" : "Odd";
printf("%s", label);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Nested Ternary
You can nest ternary operators to handle more than two outcomes, but each level of nesting makes the expression harder to read at a glance -- past two conditions, a regular if-else ladder is usually clearer.
Example: Nested Ternary
#include <stdio.h>
int main() {
int score = 75;
char *grade = (score >= 90) ? "A" : (score >= 70) ? "B" : "C";
printf("%s", grade);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: