❓ The Ternary (?:) Operator in C
Elegant shorthand for conditional logic
The ternary operator, also known as the conditional operator, is a shorthand way of writing an if-else statement in C.
It is used for making decisions based on a condition and provides a concise way to choose between two values.
📝 General Syntax
🔍 Condition
The expression that evaluates to true or false. This determines which value will be chosen.
✅ Expression if True
The value or expression returned when the condition is true (comes after the ?).
❌ Expression if False
The value or expression returned when the condition is false (comes after the :).
💡 Practical Example
int main() {
int num = 10;
char* result;
// Using the ternary operator to assign a value to result based on the condition
result = (num % 2 == 0) ? "Even" : "Odd";
// Display the result
printf("The number %d is %s.\n", num, result);
return 0;
}
📤 Output:
🔍 Step-by-Step Breakdown
Condition: (num % 2 == 0) checks if num is even by testing if the remainder when divided by 2 equals 0.
If True: If num is even (num % 2 == 0 is true), then the value assigned to result is "Even".
If False: If num is odd, the value assigned is "Odd".
Output: The result is then printed using printf, displaying whether the number is even or odd.
⚖️ Ternary vs If-Else Comparison
✅ Using Ternary Operator
Concise and readable for simple conditions
📝 Using If-Else
result = "Even";
} else {
result = "Odd";
}
More verbose but explicit
Advantages of Ternary Operator
🎯 Key Takeaways
Become a Developer in 6 Months
No degree? No problem. Treehouse Techdegrees give you the skills, the portfolio, and the certificate to land your first tech job.

If you have any doubts, Please let me know