Discussion
What will be the output of the following code −
#include <stdio.h>
#include <stdlib.h>
int main() {
union my_union {
int i;
float f;
char c;
};
union my_union* u;
u = (union my_union*)malloc(sizeof(union my_union));
u->f = 20.60f;
printf("%f", u->f);
free(u);
return 0;
}
Answer: B
Correct answer: 20.600000
The value is stored in the union's float member and read back through the same member, so no type punning is involved and the value survives intact.
It prints as 20.600000 because %f defaults to six decimal places. The bare 20.6 is what the source contains but not what printf produces without a precision specifier. Note that a union holds only one member at a time - writing u->f overwrites whatever u->i or u->c held.
No comment is present. Be the first to comment.
Loading…
Post your comment
Please log in or register to post a comment.
Examination Categories
- SSC Exams
- Banking Exams
- Teaching Exams
- Civil Services Exams
- Railways Exams
- Engineering Recruitment Exams
- Defence Exams
- State Government Exams
- Police Exams
- Insurance Exams
- Nursing Exams
- Other Government Exams
- NRA CET
- PG Entrance Exams
- Campus Placement
- MBA Entrance Exams
- CUET and UG Entrance
- Judiciary Exams
- Regulatory Body Exams
- Software Development