ProgrammingHardTCS NQT · Infosys pattern
What is printed?
What is printed?
int a = 5;
int b = 10;
int result = a > b ? a : b > 0 ? b : 0;
printf("%d", result);- A. 0
- B. 5
- C. Compile-time error: nested ternary needs explicit parentheses
- D. 10
Correct answer: D. 10
The ternary operator is right-associative, so a > b ? a : b > 0 ? b : 0 parses as a > b ? a : (b > 0 ? b : 0). Since a > b (5 > 10) is false, the whole expression evaluates the else-branch, b > 0 ? b : 0; since b > 0 (10 > 0) is true, that gives b, 10.
More C Programming questions
- What is printed? c int x = 5; int y = (x = 10) + (x = 20); printf("%d", y);
- What is printed? c int a = 1, b = 2; int result = !a == !b; printf("%d", result);
- What is printed? c int x = 10; int y = x > 5 ? x > 8 ? 1 : 2 : 3; printf("%d", y);
- What is printed? c int i = 0; int arr[5] = {10, 20, 30, 40, 50}; while (i < 5) printf("%d ", arr[i++]); printf("%d", i);
- What is printed? c int a = 5; int b = (a > 3) ? (a = 10) : (a = 20); printf("%d %d", a, b);
- What is printed? c int x = 2, y = 3, z = 4; int result = x + y z - x / y; printf("%d", result);