In C programming, determine the output of this program using a union of int and char[2].
#include
int main()
{
union A {
int i;
char ch[2];
};
union A u;
u.ch[0] = 3;
u.ch[1] = 2;
printf("%d, %d, %d
", u.ch[0], u.ch[1], u.i);
return 0;
}
-
A3, 2, 515
-
B515, 2, 3
-
C3, 2, 5
-
D2, 3, 515
Answer
Correct Answer: 3, 2, 515
Explanation
Introduction / Context: This question tests understanding of unions, byte ordering (endianness), and how writing to a char array inside a union affects the overlapping int member in C.
Given Data / Assumptions:
- union A has two members: int i and char ch[2].
- Assignments: ch[0] = 3 and ch[1] = 2.
- Output prints ch[0], ch[1], and i in that order.
- Assume a typical little-endian environment with 16-bit int for the classic result (as on many older compilers used in such questions).
Concept / Approach: In a union, all members share the same memory. On little-endian systems, the least significant byte is stored at the lowest address. With a 16-bit int, ch[0] maps to the low byte of i and ch[1] maps to the high byte of i. Therefore i = ch[0] + ch[1]256 = 3 + 2256 = 515.
Step-by-Step Solution:
Write ch[0] = 3 → low byte of i becomes 3.Write ch[1] = 2 → high byte of i becomes 2.Compute i = 2256 + 3 = 512 + 3 = 515.printf prints: 3, 2, 515.Verification / Alternative check: If int is 32-bit little-endian, the low two bytes would still be 03 and 02, giving i = 515 with higher bytes 0. Hence the printed value for i remains 515 on common little-endian systems.
Why Other Options Are Wrong:
- 515, 2, 3: Reorders fields; the program prints ch[0], ch[1], then i.
- 3, 2, 5: Ignores byte significance; 2256 is not 2.
- 2, 3, 515: Swaps ch indexes; program does not do that.
Common Pitfalls: Confusing endianness (big-endian would differ), assuming unions copy rather than overlay, or assuming chars sign-extend into the int. Here bytes are combined by position, not sign extension.
Final Answer: 3, 2, 515