in Programming in C
206 views
0 votes
0 votes
What should be the output of the  code?

 

 

#include<stdio.h>
union data
{
    int a;
    float b;
} ;
int main()
{
union data a1;
a1.a=4;
a1.b=32768.0;

printf("%d \n%f",a1.a,a1.b);
return 0;
}
in Programming in C
206 views

1 Answer

2 votes
2 votes

we know that in union only one member is activated at a time

it means it's allocate memory for size of largest member of it's

therefore in your example it allocate size of float

for better understanding, let assume int takes 2 Bytes and float takes 4 Bytes. and your system is following little endian ( for more details https://www.geeksforgeeks.org/little-and-big-endian-mystery/ )

 

a1 allocates memory like this

       
103 102 101 100

 

a1.a=4;

00000000 00000000 00000000 00000100
103 102 101 100


a1.b=32768.0; ===> Floating point ===> as per IEEE754 standard it stores as ( for understanding http://svitlanamoiseyenko.com/2017/01/17/storing-of-floating-point-numbers-in-memory/ )

01000111 10000000 00000000 00000000
103 102 101 100

 

if integer access 4 Bytes ( means size of int = 4 Bytes )

sign bit = 0 ===> value = 2$^{23}$+2$^{24}$+2$^{25}$+2$^{26}$+2$^{30}$ = 2$^{23}$[1+2+4+8+127] = 2$^{23}$[142] = 1191182336

 

if integer access 2 Bytes, if it is little endian system = last 2 Bytes = 00000000 00000000 = 0

if it is big endian system = first 2 Bytes = 01000111 10000000 = 1191182336

 

edited by

Related questions