Simple Tutorials for Smart Learning
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.
if...else
condition ? expression_if_true : expression_if_false;
If the condition is true, execute expression_if_true.
expression_if_true
If the condition is false, execute expression_if_false.
expression_if_false
#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; }
The maximum is 20
#include <stdio.h> int main() { int marks = 75; char *result = (marks >= 50) ? "Pass" : "Fail"; printf("Result: %s\n", result); return 0; }
Result: Pass
#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; }
x is Zero
int min = (a < b) ? a : b;
printf("%s", (age >= 18) ? "Adult" : "Minor");
return (x > y) ? x : y;
: