C - Unions | Unions in C | Difference between Structure and Union in C

Union is collection of variables of different data types. However, with unions, we can only store information in one field at any one time. Each element in a union is called member.
Union is a group of heterogeneous data. It is similar to structure, except that in union all the members share the same storage space in the memory. In a structure each member has their own storage space. The size of the allocated common memory in union is equal to the size of its largest member. Union is therefore used to save memory and concept is useful when it is not necessary to use all members of union at the same time.

Due to the common memory, we can’t access all the union members at the same time. Since union variable holds one member at a time , we can access only one member at a time.

Declaring a Union:

Union is declared using the keyword, union. The size of a union is the size of its largest member. This is because a sufficient number of bytes must be reserved for the largest size member.

The general syntax of declaring a union:

union union_name

{

datatype member1;

datatype member2;

…………………...

datatype membern;

};


union_name is the union name. For example, students, employees etc.


For example:

union student

{

int roll;

char name[20];

};


Declaring Union Variable:

Declaration of a union does not allocate any space in memory. To allocate memory, we need to create union variables.

union union_name

{

datatype member1;

datatype member2;

…………………...

datatype membern;

}var1, var2;


Or

 

union union_name

{

datatype member1;

datatype member2;

…………………...

datatype membern;

};

union union_name var1,var2;

union_name is the union name. For example, students, employees etc. var1, var2 etc, are the union variables.

 

For example:

union student

{

int roll;

char name[20];

}std1, std2;

 

  • Here std1, std2 are union variable.
  • Each variable can represent a 20 character string or any integer at any one time
  • The compiler will allocate the higher memory(20) bytes for the union variables
  • Only one member of the union can be assigned a value at one time. For example, std1.roll=1


Initializing Union Member:

In union, any one member can be active at a time. So, we can initialize only one of the members at one time. We can initialize the union variable at the time of declaration.


Example:

union Student

{

int roll;

char name[20];

} std1={1};  

 

Here, std1 is the union variable and is initialized its member roll to 1. Since we have not specified any member name while initializing, it initializes first element.

 

 

Programming Example:

 

#include<stdio.h>

int main()

{

union number

    {

    int n1;

    float n2;

    }; 

union number x;

printf(“Enter the value of n1:”);

scanf(“%d”,&x.n1);

printf(“Value of n1=%d”,x.n1);

printf(“\nEnter the value of n2:”);

scanf(“%f”,&x.n2);

printf(“Value of n2=%f”,x.n2);

return 0;

  }



Output:


Enter the value of n1: 15;

Value of n1=15

Enter the value of n2: 20

Value of n2=20.000000



Accessing Union Members:

To access any member of a union, we use dot operator (.) or the member access operator.

 

Syntax for accessing any union member:

union_variable_name.member

 

For example: std1.rol;

 

The following example shows how to use unions in a program

 

#include<stdio.h>

#include<string.h>

union Data

{

int i;

float f;

char str[20];

};

int main()

{

union Data x;

x.i=10;

x.f=220.5;

strcpy(x.str, “C programming”);

printf(“x.i : %d\n”, x.i);

printf(“x.f : %f\n”, x.f);

printf(“x.str : %s\n”, x.str);

return 0;

}


When the above code is compiled and executed, it produces the following result:


x.i : 1917853763

x.f : 4122360580327794860452759994368.000000

x.str : C programming


Here, we can see that the values of i and f members of union got corrupted because the final value assigned to the variable has occupied the memory location and this is the reason that the value of str member is getting printed very well.

Now let's look into the same example once again where we will use one variable at a time which is the main purpose of having unions-


#include<stdio.h>

#include<string.h>

union Data

{

int i;

float f;

char str[20];

};

int main()

{

union Data x;

x.i=10;

printf(“x.i : %d\n”, x.i);

x.f=220.5;

printf(“x.f : %f\n”, x.f);

strcpy(x.str, “C programming”);

printf(“x.str : %s\n”, x.str);

return 0;

}


When the above code is compiled and executed, it produces the following result :

x.i : 10

x.f : 220.500000

x.str : C Programming


 

Here, all the members are getting printed very well because one member is being used at a time.


Advantages of using a Union:

Some of the reasons to use union is:

1. It allocates the space in the memory of the data members, who have the highest memory, i.e., in this case, the memory consumption is less.

2. Through this, you can hold data of only one data member.

3. The last variable can be accessed directly in the union.

4. When you have to use the same location for one or more data members, then unions are used.

 

Disadvantages of using a Union:

Some of the disadvantages of the union:

1. Only one member can be accessed at a particular period of time.

2. Only one storage space is assigned to all the variables.

3. All the variables cannot be assigned with varying values at a time.


Similarities between Structure and Union:

 

The following are the similarities between structure and union:

  • Both structure and union are the custom data types ( user defined data types) that store different types of data together as a single unit.
  • The structure and union members can be objects of any type including other structures, unions, or arrays.
  • Both structures and unions can be passed by value to a function and returned to the value by functions. The argument will need to have the same type as the function parameter.
  • ‘.’ operator or selection operator is used for accessing member variables inside both structure and union.



Difference between Structure and Union in C:


Structure

Union

The struct keyword is used to define a structure.

The union keyword is used to define a union.

When the variables are declared in a structure, the compiler allocates memory to each variables member

When the variable is declared in the union, the compiler allocates memory to the largest size variable member.

Every member within structure is assigned a unique memory location.

In union, all the data members share a memory location.

Changing the value of one data member does not affect other data members in the structure.

Changing the value of one data member affects the value of other data members.

We can access or retrieve any member at a time.

We can access or retrieve only one member at a time.

We can initialize multiple members at a time.

We can initialize only one of the member at a time

 A structure’s total size is the sum of the size of every data member.

A union’s total size is the size of the largest data member.





Post a Comment

0 Comments