🔀 Ternary (Conditional) Operator
Last Updated: Jan 2026
The Ternary Operator is a short way to write if...else conditions in one line. It checks a condition and returns one of two values based on whether it's true or false.
Syntax
condition ? value_if_true : value_if_false;
condition ? if_true_another_condition ? value_if_true_another_condition : value_if_false_another_condition : value_if_false;
If the condition is true → returns the first value.If false → returns the second value.
Example Basic
int age = 18;
char *result = (age >= 18) ? "You can vote" : "You cannot vote";
printf(result); // Output: You can vote
Example Nested
int marks = 85;
char *grade = marks >= 90 ? "A+" : marks >= 75 ? "A" : marks >= 50 ? "B" : "Fail";
printf(grade); // Output: A
👨💻 Quick Practice
- Check if a number is even or odd using a ternary operator.
- Print "Pass" if marks ≥ 40 else "Fail".
- Create a variable isLoggedIn and print "Logout" if true else "Login".
- Make a nested ternary for temperature: 30 → "Hot", 15-30 → "Warm", else → "Cold".
