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;
condition ? value_if_true : value_if_false do in C++?int x = 10, y = 20; int max = (x > y) ? x : y; std::cout << max;
int a = 5, b = 8; int result = a > b ? a, b; std::cout << result;
result? int x = 0; int y = 5; int result = (x != 0) ? (y / x) : y * 2; std::cout << result;
Pass the test and this pattern moves unknown