Concept Flow - Ternary operator
Evaluate condition
Yes/No
True
Result if true
Assign or use result
The ternary operator checks a condition and chooses one of two values based on whether the condition is true or false.
int a = 10; int b = 20; int max = (a > b) ? a : b; std::cout << max;
| Step | Condition (a > b) | Result if True | Result if False | Value assigned to max | Output |
|---|---|---|---|---|---|
| 1 | 10 > 20 | 20 | 10 | 10 | 10 |
| 2 | End | - | - | - | - |
| Variable | Start | After Ternary | Final |
|---|---|---|---|
| a | 10 | 10 | 10 |
| b | 20 | 20 | 20 |
| max | uninitialized | 10 | 10 |
Ternary operator syntax: condition ? value_if_true : value_if_false; It evaluates the condition once. If true, returns value_if_true; else returns value_if_false. Used for simple conditional assignments. Example: max = (a > b) ? a : b;