ProgrammingHardIBM · Deloitte pattern
What is printed?
What is printed?
int x = 5;
int y = (x = 10) + (x = 20);
printf("%d", y);- A. 30
- B. 20
- C. Undefined behaviour: x is assigned twice in the same expression, unsequenced relative to each other
- D. 10
Correct answer: C. Undefined behaviour: x is assigned twice in the same expression, unsequenced relative to each other
Both (x = 10) and (x = 20) are side effects on the SAME object x, and the + operator does not sequence its two operand evaluations relative to each other. Two unsequenced writes to the same scalar is undefined behaviour, regardless of what any particular compiler happens to compute for y.
More C Programming questions
- 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);
- Assume a 64-bit LP64 ABI. What is printed? c int arr[5] = {1, 2, 3, 4, 5}; int start = arr; int end = arr + 5; int sum = 0; for (int p =…