Difference Between Structure and Union With Examples

Difference Between Structure and Union 

This guide will teach you major differences between Structure and union in c programming language, what makes difference in Structure and Union will be explained . Let's go through guide with help of  Structure and union definitions




Structure vs union

Structure : 

Structure is a user defined data type that available in c that allows to combine different kind of items,generally it is used to represent a record 

For suppose if we want to keep track of employee details in an organization.Then you need to track some important information regarding employees like employee_id, name,age and gender etc.. 


Syntax :

struct [structure tag]
{
member definition;
member1 definition;
...........
..........
member N definition;
}[one or more structure variables] ; 



Union:

A union is data type that allows to store different data types in same memory location.union provide best way of using same memory location for multiple times

Syntax :

union[union tag]
{
member definition;
member1 definition;
...........
..........
member N definition;
}[one or more union variables] ; 




Differences :


                        Structure
                               Union

1.In struct each member allocates separate memory
For example check below
struct employee
{
 int employee_id;
char gender;
float salary;
} employee1;
Differnce between struct and union



1.Union allocates piece of memory that is large enough to hold the largest variable of type
For example check below
union employee
{
 int employee_id;
char gender;
float salary;
} employee1;
Differnce between struct and union




 2.Altering the value of any member in structure will not affect other members in structure


2.Altering the value of any member can affect other members in union

3. In structure all members get memory allocated . So any member can be retrieved at any time


3. In union while retrieving data from a union type is being retrieved must be type recently used

4.We can initialize one or more number of members at a time

 4. A union may only be initialized with a value of the type of its first member; thus union employee1 mentioned above (during example declaration in point 1) can only be initialized with an integer value


5.It has less ambiguity


5.It has more ambiguity reason being memory is shared 


 6.Structure can not be implemented in shared memory


 6.union is best environment for shared memory

 7.To define a structure we use keyword "struct"


7.To define a union we use keyword "union"

8.We can implement Self referential structure by Data Structure


8.Self referential union can not be implemented





Hope this guide will help you out difference between Structure and Union . If you have any doubt regarding this topic or if anything wrong you can comment below 















0 comments