C unions — what is printed after storing a float in a union and reading it back?
#include
#include
int main()
{
union test
{
int i;
float f;
char c;
};
union test *t = (union test *) malloc(sizeof(union test));
t->f = 10.10f;
printf("%f", t->f);
return 0;
}
Assume malloc succeeds.
-
A10
-
BGarbage value
-
C10.100000
-
DError
Answer
Correct Answer: 10.100000
Explanation
Introduction / Context:This question focuses on unions in C and accessing the same member that was most recently written. It checks whether learners understand that reading back the same active member yields the stored value, subject to normal floating-point formatting in printf.
Given Data / Assumptions:
- t points to a valid union test object.
- t->f is assigned 10.10f.
- printf uses "%f" to print a float (promoted to double on call).
Concept / Approach:If you write to one member of a union and then read the same member, you get the stored value. Using a different member without writing it is not meaningful. printf("%f") will display the value with default precision (typically 6 places after the decimal), so 10.10f prints as 10.100000 by default.
Step-by-Step Solution:
1) Allocate union test; assignment to t->f sets the union's active member to float.2) Printing the same member t->f is defined behavior.3) printf formats the float as a fixed-point string with 6 decimals.Verification / Alternative check:Formatting can be changed using "%.2f" to print "10.10". With the default "%f", expect "10.100000".
Why Other Options Are Wrong:
- 10: Not the default "%f" precision.
- Garbage value: Would occur only if reading a different member than written.
- Error: The code is valid if malloc succeeds.
Common Pitfalls:Assuming unions always cause aliasing issues; here the same member is consistently used, which is fine.
Final Answer:10.100000