LERAN C PROGRAMMING

Learn one of the most powerful programming languages in the world and become a rockstar developer.

Unions


Union is a collection of variables of different data types. Union is useful for representing logically related information of different data types.
Union and Structure are almost similar in terms of defining and declaring them but the basic differance between structure and union is that in structure memory is allocated seperately for each member while in union only one memory block is allocated for all members.

In union all members share one common memory space. Compiler allocates memory space such that it can accommodate largest member of the union.
In union only one data member can be accessed at a time because all data member share one common memory. 

SYNTAX:

union union_name
{
   datatype variable1;
   datatype variable2;
   ..................
   datatype variableN;
};

Union can be declared using union keyword.
Members of the union must be enclosed between curly brackets and declaration of union must end with semicolon.

EXAMPLE:

union Item
{
    int qty;
      float price;
};

Here,
Item is a union having two members declared inside it.

Variable of union can be declared using union keyword and union name.

SYNTAX:

union union_name Var1,Var2,Var3;

EXAMPLE:

union Item I1, I2, I3; 

In above example union Item having two members.

Member Name Data Type Size in Byte
qty int 2
price float 4
Total Memory Occupied 4

Here largest memory occupied is 4 bytes so 4 bytes allocated to each union variable I1, I2 and I3.
Members of the union can be accessed using variable name followed by dot (.) operator followed by member name.

SYNATX:

union_variable_name.member_name;

 

EXAMPLE:

I1.qty=5;
I1.price=50.50;

Why this difference in the size of union and structure variables?

Here, the size of sJob is 40 bytes because

  • the size of name[32] is 32 bytes
  • the size of salary is 4 bytes
  • the size of workerNo is 4 bytes

However, the size of uJob is 32 bytes. It's because the size of a union variable will always be the size of its largest element. In the above example, the size of its largest element, (name[32]), is 32 bytes.


Only one union member can be accessed at a time 

You can access all members of a structure at once as sufficient memory is allocated for all members. However, it's not the case in unions. You can only access a single member of a union at one time. Let's see an example.

#include <stdio.h>
union Job
{
   float salary;
   int workerNo;
} j;
int main()
{
   j.salary = 12.3;
   j.workerNo = 100;
   printf("Salary = %.1f\n", j.salary);
   printf("Number of workers = %d", j.workerNo);
   return 0;
}

Output

Salary = 0.0
Number of workers = 100

Notice that 12.3 was not stored in j.salary.



Previous Next
x
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Privacy Policy That's Fine