What is the output of the following code in c?

  • A+
Category:Languages
#include <stdio.h> int main() {   union Data   {     char str[20];         int i;     float f;   }data;    data.i=20;   data.f=220.5;   printf("%d/n",(data.i));    return 0; } 

The output is:1130135552. I used gcc complier on Ubuntu 16.04 LTS.

Can someone explain the output?

The members data.i and data.f occupy same memory location, so output should be 220. But why output is 1130135552?

 


As you are already aware that union shares memory location between the members inside. In case of union compiler allocated the memory equal to the max size of the member and use the same memory for all the members.

Hence when you execute data.f=220.5;, shared memory location between i and f holding data.i=20; got overwritten to a new value (220.5) with binary representation as follows :

What is the output of the following code in c?

Now again, when this value is read as a signed integer int it will be interpreted without conversion as 1130135552 in decimal representation. Hence you are getting 1130135552.

Further if you want to use all members of union, then struct is the answer.

struct Data {     char str[20];     int i;     float f; } data;  data.i=20; data.f=220.5; printf("%d/n",data.i); 

For more information on union and struct Please refer the following from Difference between Structure and Union: What is the output of the following code in c?

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: