The union in c stores one data at a time

If the size of the union allocated in memory is equal to the largest member of the data type in bytes, then can someone tell me how the compiler stores and retrieves two datas double d and int i (total 8 + 4 bytes) (double on my machine has 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**
+4
source share
5 answers

, , - " ". , IEEE 754 , . , 15.5 : 402F000000000000. , . 200 , . 402F0000000000C8. , , IEEE754 15.500000000000355, 15.5, , double, int.

, , - undefined ++, , ++ 11 ( , ), , . C , , , .

+7

, , , .

, , , :

obj.d=100000000000000;
obj.i=0xffffffff;

double:

Value stored in d is 100000059097087.984375
+3

, , . :

#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));

   obj.d=17.5;

   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));

   obj.i=300;

   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));

}

:

$ ./main 

Value stored in d is 15.500000
Value stored in i is 200
 size of obj is 8 
Value stored in d is 17.500000
Value stored in i is 0
 size of obj is 8 
Value stored in d is 17.500000
Value stored in i is 300
 size of obj is 8 

, 0 ! , (?) .

undefined , , , , , .. ..

Edit:

, - , , ? 200.

, ? , "int", "" , 17.5. . : . "Imreal" .

+2

i, d , .

obj.i=200;  

, , . obj.d %f undefined, , obj, int.

+1

obj.i, obj.d - undefined, C, .

, , , . , , . :

printf("\nValue stored in d is %.17f",obj.d);

:

Value stored in d is 15.50000000000035705
+1

All Articles