C Notes
Learn the ternary (conditional) operator (?:) in C. Understand syntax, nested ternary expressions, when to use ternary vs if-else, and practical examples for concise conditional logic.
The ternary operator (?:) is C's only operator that takes three operands, which is why it's called "ternary." It's essentially a compact if-else statement that fits in a single expression. When used appropriately, it makes code concise and elegant — but when overused or nested deeply, it can turn into an unreadable mess. Let's explore when and how to use it effectively.
Syntax of the Ternary Operator
The operator evaluates the condition. If it's true (non-zero), it returns expression_if_true. Otherwise, it returns expression_if_false.
#include <stdio.h>
int main() {
int age = 20;
// Ternary operator
char *status = (age >= 18) ? "Adult" : "Minor";
printf("%s\n", status);
// Equivalent if-else
// if (age >= 18)
// status = "Adult";
// else
// status = "Minor";
return 0;
}Adult
Basic Examples
#include <stdio.h>
int main() {
int a = 10, b = 20;
// Find maximum
int max = (a > b) ? a : b;
printf("Max of %d and %d = %d\n", a, b, max);
// Find minimum
int min = (a < b) ? a : b;
printf("Min of %d and %d = %d\n", a, b, min);
// Absolute value
int num = -15;
int abs_val = (num < 0) ? -num : num;
printf("Absolute value of %d = %d\n", num, abs_val);
// Even or Odd
int x = 7;
printf("%d is %s\n", x, (x % 2 == 0) ? "even" : "odd");
return 0;
}Max of 10 and 20 = 20 Min of 10 and 20 = 10 Absolute value of -15 = 15 7 is odd
Ternary Inside printf()
One of the most common uses is directly inside printf() for conditional output:
#include <stdio.h>
int main() {
int items = 1;
printf("You have %d item%s in your cart\n", items, (items == 1) ? "" : "s");
items = 5;
printf("You have %d item%s in your cart\n", items, (items == 1) ? "" : "s");
// Grade display
int score = 85;
printf("Score: %d - %s\n", score,
(score >= 90) ? "Excellent" :
(score >= 80) ? "Good" :
(score >= 70) ? "Average" : "Below Average");
return 0;
}You have 1 item in your cart You have 5 items in your cart Score: 85 - Good
Nested Ternary Operator
You can nest ternary operators for multiple conditions, though readability suffers quickly:
#include <stdio.h>
int main() {
int num = 0;
// Nested ternary: positive, negative, or zero
char *sign = (num > 0) ? "positive" :
(num < 0) ? "negative" : "zero";
printf("%d is %s\n", num, sign);
// Finding largest of three numbers
int a = 15, b = 42, c = 28;
int largest = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);
printf("Largest of %d, %d, %d = %d\n", a, b, c, largest);
// Letter grade
int marks = 72;
char grade = (marks >= 90) ? 'A' :
(marks >= 80) ? 'B' :
(marks >= 70) ? 'C' :
(marks >= 60) ? 'D' : 'F';
printf("Marks: %d, Grade: %c\n", marks, grade);
return 0;
}0 is zero Largest of 15, 42, 28 = 42 Marks: 72, Grade: C
Ternary Operator vs if-else
| Aspect | Ternary (?:) | if-else |
|---|---|---|
| Returns a value | Yes — it's an expression | No — it's a statement |
| Can be used in assignments | Directly | Requires separate assignment |
| Readability (simple) | Good | Good |
| Readability (complex) | Poor | Better |
| Can contain statements | No (only expressions) | Yes |
| Multiple statements | Not possible | Yes (with braces) |
When to Use Ternary
#include <stdio.h>
int main() {
int x = 5;
// GOOD: Simple conditional assignment
int result = (x > 0) ? x : -x;
// GOOD: Inside function arguments
printf("Value is %s\n", (x > 0) ? "positive" : "non-positive");
// GOOD: Conditional initialization
int max_val = (x > 10) ? 10 : x; // Cap at 10
// BAD: Complex logic (use if-else instead)
// int val = (a > b) ? (c > d ? (e > f ? g : h) : (i > j ? k : l)) : m;
printf("result=%d, max_val=%d\n", result, max_val);
return 0;
}Value is positive result=5, max_val=5
When to Use if-else Instead
#include <stdio.h>
int main() {
int score = 85;
// When you need multiple statements
if (score >= 60) {
printf("Passed!\n");
printf("Congratulations!\n");
// Can't do this with ternary
} else {
printf("Failed.\n");
printf("Better luck next time.\n");
}
return 0;
}Passed! Congratulations!
Ternary as an Lvalue? No!
Unlike some other languages, you cannot use the ternary operator on the left side of an assignment in standard C:
#include <stdio.h>
int main() {
int a = 5, b = 10;
int flag = 1;
// This WON'T compile in standard C:
// (flag ? a : b) = 100; // ERROR!
// Instead, use a pointer trick or if-else:
*(flag ? &a : &b) = 100; // Works! Assigns to a
printf("a=%d, b=%d\n", a, b);
return 0;
}a=100, b=10
Type Rules
Both expressions in a ternary must be compatible types. If they differ, the usual type promotion rules apply:
#include <stdio.h>
int main() {
int condition = 1;
// int and float: result is float
float result = condition ? 5 : 3.14;
printf("Result: %f\n", result); // 5.000000 (int 5 promoted to float)
// char and int: result is int
int val = condition ? 'A' : 100;
printf("Value: %d\n", val); // 65
return 0;
}Result: 5.000000 Value: 65
Practical Examples
Clamping a Value to a Range
#include <stdio.h>
int clamp(int value, int min, int max) {
return (value < min) ? min : (value > max) ? max : value;
}
int main() {
printf("clamp(5, 0, 10) = %d\n", clamp(5, 0, 10));
printf("clamp(-3, 0, 10) = %d\n", clamp(-3, 0, 10));
printf("clamp(15, 0, 10) = %d\n", clamp(15, 0, 10));
return 0;
}clamp(5, 0, 10) = 5 clamp(-3, 0, 10) = 0 clamp(15, 0, 10) = 10
Toggling Between Two Values
Iteration 1: toggle = 1 Iteration 2: toggle = 0 Iteration 3: toggle = 1 Iteration 4: toggle = 0 Iteration 5: toggle = 1 Iteration 6: toggle = 0
Formatting Output Alignment
Student Results: Student Score Status ------- ----- ------ Student 1 95 PASS Student 2 67 PASS Student 3 82 PASS Student 4 45 FAIL Student 5 91 PASS Student 6 73 PASS
Precedence and Associativity
The ternary operator has very low precedence — just above assignment operators. It associates right-to-left:
#include <stdio.h>
int main() {
int a = 1, b = 2;
// Ternary has lower precedence than most operators
int result = a + b > 2 ? 10 : 20; // (a + b) > 2 is evaluated first
printf("result = %d\n", result); // (3 > 2) ? 10 : 20 = 10
// Right-to-left associativity
// a ? b : c ? d : e is a ? b : (c ? d : e)
int x = 0, y = 1;
int val = x ? 1 : y ? 2 : 3; // x ? 1 : (y ? 2 : 3) = 0 ? 1 : (1 ? 2 : 3) = 2
printf("val = %d\n", val);
return 0;
}result = 10 val = 2
Interview Questions
Q1: Can the ternary operator replace all if-else statements?
No. The ternary operator can only be used for expressions that return a value. It cannot execute multiple statements, declare variables, or use break/continue/return. Use if-else when you need multiple actions in each branch or when the logic is complex enough that ternary becomes unreadable.
Q2: What is the output of printf("%d", 1 ? 2 : 3, 4)?
The output is 2. The ternary expression 1 ? 2 : 3 evaluates to 2 because the condition (1) is true. The , 4 is simply an extra argument to printf that has no corresponding format specifier, so it's ignored.
Q3: Is (a > b) ? a : b safe for finding the maximum of two numbers?
Yes, for simple scalar types. However, it evaluates each expression exactly once (unlike a macro #define MAX(a,b) ((a)>(b)?(a):(b)) where if you pass a++, it could increment twice). For function-like behavior without side effects, this is perfectly safe.
Q4: What's wrong with deeply nested ternary operators?
While syntactically valid, deeply nested ternary operators are extremely hard to read and maintain. Code like a ? b ? c : d : e ? f : g requires mental parsing of multiple levels. If you have more than one level of nesting, prefer if-else or switch statements for clarity.
Q5: What is the associativity of the ternary operator?
Right-to-left. This means a ? b : c ? d : e is parsed as a ? b : (c ? d : e), not (a ? b : c) ? d : e. This natural right-to-left grouping enables clean chaining for else-if style logic.
Summary
- The ternary operator
?:is a concise alternative to simple if-else for value selection - Syntax:
condition ? true_expression : false_expression - It's an expression (returns a value), unlike if-else which is a statement
- Use it for simple conditional assignments and inline output formatting
- Avoid nesting beyond one level — deeply nested ternary is unreadable
- Both expressions must be type-compatible; promotion rules apply automatically
- Has very low precedence (above assignment) and right-to-left associativity
- Cannot replace if-else when multiple statements or side effects are needed
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Ternary Operator in C Programming.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this C Programming topic.
Search Terms
c-programming, c programming, programming, operators, ternary, operator, ternary operator in c programming
Related C Programming Topics