Concept Flow - Ternary operator
Evaluate condition
Yes/No
True expr
Result assigned
The ternary operator checks a condition, then chooses one of two expressions to evaluate and assign based on that condition.
int a = 5; int b = 10; int max = (a > b) ? a : b; printf("%d", max);
| Step | Condition (a > b) | Condition Result | Expression Chosen | Value Assigned to max | Output |
|---|---|---|---|---|---|
| 1 | 5 > 10 | False | b | 10 | |
| 2 | N/A | N/A | N/A | N/A | 10 |
| Variable | Start | After Step 1 | Final |
|---|---|---|---|
| a | 5 | 5 | 5 |
| b | 10 | 10 | 10 |
| max | uninitialized | 10 | 10 |
Syntax: condition ? expr_if_true : expr_if_false; Evaluates condition first. If true, evaluates and returns expr_if_true. If false, evaluates and returns expr_if_false. Used for concise if-else assignments.