C Ternary Operator (? : ) – A Shorter Way to Write if...else
The ternary operator in C is a compact, one-line version of an if...else
statement. It helps you write cleaner and more concise code when dealing with conditional assignments or outputs.
Syntax of the Ternary Operator
condition ? expression_if_true : expression_if_false;
Meaning:
If the condition is true, execute
expression_if_true
.If the condition is false, execute
expression_if_false
.
Simple Example
#include <stdio.h>
int main() {
int a = 10, b = 20;
int max = (a > b) ? a : b;
printf("The maximum is %d\n", max);
return 0;
}
Output:
The maximum is 20
Another Example – Pass/Fail
#include <stdio.h>
int main() {
int marks = 75;
char *result = (marks >= 50) ? "Pass" : "Fail";
printf("Result: %s\n", result);
return 0;
}
Output:
Result: Pass
Nesting Ternary Operators
#include <stdio.h>
int main() {
int x = 0;
char *result = (x > 0) ? "Positive" : (x < 0) ? "Negative" : "Zero";
printf("x is %s\n", result);
return 0;
}
Output:
x is Zero
When to Use the Ternary Operator
✅ Use Case | 📝 Example |
---|---|
Assign value conditionally | int min = (a < b) ? a : b; |
Print messages | printf("%s", (age >= 18) ? "Adult" : "Minor"); |
Return values in functions | return (x > y) ? x : y; |
Best Practices
Do | Don’t |
---|---|
Use it for simple logic | Avoid complex nested conditions |
Use parentheses for clarity | Don’t overuse it in long expressions |
Keep it readable | Don’t replace all if...else with it |
Common Mistakes
Mistake | Problem |
---|---|
Using it for actions instead of values | Ternary is an expression, not a statement |
Forgetting : | Leads to compiler errors |
Nesting without parentheses | Makes code unreadable and error-prone |