423 views
0 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;
}

1 Answer

2 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
Position:
Show:

Related questions

1 1 vote
1 1 answer
1.4k
1.4k views
Human asked Oct 8, 2018
1,431 views
how the answer is 23699?For column major order I get answer as 80039.Even if i go by row major order the answer I get is 23599
2 2 votes
1 1 answer
739
739 views
Ravi kumar singh asked Jan 19, 2018
739 views
Let A be an array with 5 rows and 10 columns. Assume base address is 100 and each element requires 4 bytes. Find the address of A [4,9], if array is stored in row major o...
0 0 votes
1 1 answer
489
489 views
targate2018 asked Nov 9, 2017
489 views
Explain the behaviour of following code:int main(){int *j=0;{int i=10;j=&i;}printf("%d",*j);} a. output is 10. j pointed to address of i, so it was not freed.b. output ma...
0 0 votes
2 2 answers
2.7k
2.7k views
Satwik Mishra 1 asked Sep 20, 2017
2,686 views
#include<stdio.h>int f(int x,int *py,int ppz){ int y,z; ppz+=1; z= ppz; *py+=2; y=*py; x+=3; return(x+y+z);}void main(){ int c,*b, a; c=4; b=&c; a=&b; print...