The below code results in:
0.000000
10
What is being returned from 'data' in this case? I know n.data.idata
and n.data.fdata
would be the correct usage, I'm just curious as to why the integer value works in this case and the float value does not.
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
union container
{
int idata;
float fdata;
} data;
struct node *next;
} Node;
int main()
{
Node i = {.data.idata = 10};
Node n = {.data.fdata = 10.0};
printf("%f\n", n.data);
printf("%d\n", i.data);
printf("\nExiting program...\n");
return 0;
}
Let's ignore the obvious undefined behavior for a moment, which happens because an incorrect type is passed to the printf function for the specifier f
. That type being an anonymous union.
Specifier f
assumes a default argument promotion from float to double, which doesn't happen in this case, because a union data
is passed to the function. So the function receives the union data
which consists of 4 bytes and represents a float, but tries to print 8 bytes, because it expects a double. The result is a nonsense value, in your case 0.0.
(This answer assumes IEEE 754, and sizeof(int)<=4)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With