Difference between Structure and Union

In this tutorial you will learn about difference between structure and union.

 

Structure and union both are user defined data types which contains variables of different data types. Both of them have same syntax for definition, declaration of variables and for accessing members. Still there are many difference between structure and union. In this tutorial we will take a look on those differences.
 

Difference between Structure and Union

Structure
Union
In structure each member get separate space in memory. Take below example.
 
struct student
{
      int rollno;
      char gender;
      float marks;
}s1;
 
The total memory required to store a structure variable is equal to the sum of size of all the members. In above case 7 bytes (2+1+4) will be required to store structure variable s1.
 
In union, the total memory space allocated is equal to the member with largest size. All other members share the same memory space. This is the biggest difference between structure and union.
 
union student
{
      int rollno;
      char gender;
      float marks;
}s1;
 
In above example variable marks is of float type and have largest size (4 bytes). So the total memory required to store union variable s1 is 4 bytes.
 
We can access any member in any sequence.
 
s1.rollno = 20;
s1.marks = 90.0;
printf(“%d”,s1.rollno);
 
The above code will work fine but will show erroneous output in the case of union.
We can access only that variable whose value is recently stored.
 
s1.rollno = 20;
s1.marks = 90.0;
printf(“%d”,s1.rollno);
 
The above code will show erroneous output. The value of rollno is lost as most recently we have stored value in marks. This is because all the members share same memory space.
 
All the members can be initialized while declaring the variable of structure.
Only first member can be initialized while declaring the variable of union. In above example we can initialize only variable rollno at the time of declaration of variable.
 
 
 
Difference between Structure and Union
 

Difference between Structure and Union

If you found anything incorrect or have any doubts regarding above difference between structure and union tutorial then comment below.

15 thoughts on “Difference between Structure and Union

  1. muthu prasanth

    superb.i like this very much and easily understand structure and union .thanks for explain with example

    Reply
  2. neha daharwal

    so good i am understand diff. Bw structure and union

    Reply
  3. Sujitha K`

    Sir,
    Your explanation is clear cut. But I have one doubt.
    In Which situation I have to use union instead of structure. And how can I analyze it?

    Reply
  4. shailesh

    1st,2nd points are ok but 3rd point is wrong since we can initialize any variable but only one variable not all.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *