Reputation: 3831
In the below code, if I print the values of union members the unassigned member int i;
outputs 515
. I found out that it gives the positional weight of the whole union.
Q :-But if that is declared as float i;
it outputs 0.000
. Any particular reason for this behaviour. How this works?
#include<stdio.h>
int main()
{
union a
{
float i;
char ch[2];
};
union a u;
u.ch[0] = 3;
u.ch[1] = 2;
printf("%d, %d, %f\n", u.ch[0], u.ch[1], u.i);
return 0;
}
Upvotes: 1
Views: 118
Reputation: 91
By using a union, this program is making two different data types (in this case, int/float and char[]) share the same memory area. Next, the program is assigning the memory area as an char and then reading it back as an int/float. This can succeed only if the value written as char, "makes sense" in the context of the data type in which it is read back. As you have observed, for "int" it might return some value as C does not apply any special encoding for integer values (but, also see twos-complement). However, real numbers are typically encoded using the IEEE754 standard and hence, the value that is read back, depends on what was decoded. I think this may be also compiler dependent as I'm seeing a "nan" (not-a-number) for the same code.
#include<stdio.h>
int main()
{
union a
{
float i;
char ch[2];
};
union a u;
float f = 0.0;
u.ch[0] = 3;
u.ch[1] = 2;
printf("%d, %d, %f, %f\n", u.ch[0], u.ch[1], u.i, f);
return 0;
}
Output: 3, 2, nan, 0.000000
Upvotes: 2