In C, a union shares storage among its members. For the union below, values are assigned sequentially to a and b. What will be printed when v.a is output?
#include
int main()
{
union var
{
int a, b;
};
union var v;
v.a = 10;
v.b = 20;
printf("%d
", v.a);
return 0;
}
-
A10
-
B20
-
C30
-
D0
Answer
Correct Answer: 20
Explanation
Introduction / Context: Unions in C overlay their members in the same memory location, so writing to one member overwrites the storage seen by the others. This question tests that understanding.
Given Data / Assumptions:
- union var { int a, b; } has members sharing storage.
- Assignments are v.a = 10; then v.b = 20.
- Print v.a afterwards.
Concept / Approach: The last write into the union’s shared storage sets the bits seen by all members. After writing v.b = 20, both a and b see the same bit pattern, which corresponds to 20 when interpreted as int.
Step-by-Step Solution:
Initial write: v.a = 10 stores the bit pattern of 10 Overwrite: v.b = 20 replaces the same storage with the bit pattern of 20 Reading v.a now reads that same storage -> 20Verification / Alternative check: Printing v.b immediately after would also show 20, confirming the shared memory behavior of unions.
Why Other Options Are Wrong:
- 10: Ignores the later overwrite by v.b = 20.
- 30: No arithmetic addition occurs; union does not combine values.
- 0: No zeroing of memory takes place here.
Common Pitfalls: Assuming unions keep independent values like structs; they do not. Only the most recent write is represented in shared storage.
Final Answer: 20