Tuesday 11 November 2014

Structure vs Union vs Enumeration

Q. What is the differences between structure, union and enumeration and how  and when to use them?

Ans :  These three are different-different data structure I would say. These all three can contain different different member variables like int , float ,char etc...

Difference between structure and union is that the memory which is allocated to the structure is equal to the memory needed by its all member variables and some structure padding. I will talk about structure padding in my future posts. But the size of the memory which is allocated to the union is equal to maximum of the memory needed by its individual members. 

Structures always have their all member variables active. But in union only one of its member can be active. Only one memory block that is equal to the size of the maximum size among all the member variables are allocated but in the case of structures they are allocated the space which can handle all of its members simultaneously.

Ex.  struct Car{
             int speed;
             int engine_type;
             char model ;  // a or b or c

      }

The size of the strucure will be at least the size of all the member variables plus some structure padding for alligning the structure to memory addresses which ends at the complete nibble or byte or word etc. It depends on the processor type 32 bit or 64 bit and many other things. But for sure the size will be greater or equal to the sum of the size of all the variables here the size of Car is int(4) assume so
         
                       4+4+1(char)=9 . So size will be >=9.

Ex.
           union Car{  
             int speed;
             int engine_type;
             char model ;  // a or b or c

      }

But in union only the size of the maximum size variable will be allocated to the car and that is 4 for integer in this case. At a time Car can have only speed ,engine_type or model by using union. By using structure it will have all three attributes active at the same time.


Enumeration is also contains a single value from its all values. These all values should be of similar types. But in the case of union that can be of different types. These all values can be assigned numbers and then they will be treating as numbers. If not assigned explicitly the values will be assigned starting from 0 then 1 and so on.

Ex:     enum e { sunday, monday};

then sunday will be equal 0 and monday will be equal 1 etc....  Here e will be either monday of sunday means either 0 or 1 ....


No comments:

Post a Comment

Related Posts

Related Posts Plugin for WordPress, Blogger...