Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

union in c stores one data at a time

Tags:

c++

c

unions

If size of the union allocated in memory is equal to the biggest data type member in bytes then could anyone tell me how compiler is storing and fetching two datas double d and int i (total 8+4 bytes) (double on my machine is of 8 bytes) .

#include<stdio.h>
union test {

    int i;
    double d;

};

int main()
{
   union test obj;
   obj.d=15.5;
   obj.i=200;

   printf("\nValue stored in d is %f",obj.d);
   printf("\nValue stored in i is %d",obj.i);
   printf("\n size of obj is %d ",sizeof(obj));

}

**Output is : Value stored in d is 15.500000
Value stored in i is 200
 size of obj is 8**
like image 882
theartist33 Avatar asked Dec 09 '22 02:12

theartist33


1 Answers

The way it can store both is "pure luck". I'm just going to assume your computer architecture uses IEEE 754 floating point numbers and try to explain what you're seeing. Your union really does use only eight bytes, but 15.5 looks like this in hex: 402F000000000000. As you can see the lower four bytes are completely zero. Now let's set the lowest four bytes to an integer 200 and see what happens to the eight byte value. That gives us 402F0000000000C8. Now say you read all eight bytes back as a double now, in IEEE754 you get 15.500000000000355 which when printed will round off to 15.5 making it appear that the union can store both a double and an int.

All that said accessing both members of the union like that is undefined behavior in C++ at least up to C++11 (even though it behaves in the logical way on all platforms I'm aware of), so this is simply one possible explanation for the behavior you observe. In C it appears to be completely legal though.

like image 119
Mark B Avatar answered Dec 24 '22 15:12

Mark B