a.y
is a char but here
printf("%f ",a.y);
you print it as if it is a double
. That is undefined behaviour, i.e. you can get any kind of output.
Always use the correct format specifier.
Make sure to observe compiler warnings! For gcc I get
main.cpp: In function 'main':
main.cpp:12:10: warning: format '%f' expects argument of type 'double', but argument 2 has type 'int' [-Wformat=]
12 | printf("%f ",a.y);
| ~^ ~~~
| | |
| | int
| double
| %d
which tells that something is all wrong.
If you change the code to
#include <stdio.h>
union p{
int x;
char y;
float z;
};
int main(){
union p a;
a.y = 60;
a.x = 12;
printf("%.200f ",a.z);
printf("%d ",a.y);
printf("%d",a.x);
}
the code becomes valid C code and gives this result:
0.00000000000000000000000000000000000000000001681558157189780485108475499947899357536314330251818926108481940667749299223032721783965826034545898437500000000000000000000000000000000000000000000000000000 12 12
on most little endian machines.