16-12 – Unions in C language

by subbu on October 1, 2014

In this session we are going to discourse another user defined type called union. The structure and the definition of union and struct are similar but, differ in functionality.

Union Syntax

Like a struct, even a union can have different members belongs to different types like variables, arrays, pointers, structs and unions.

The only difference among struct and union is in the memory allocation of members. An instance belongs to struct has all the members as per the definition but, it is not the case with the union, an instance belongs to union has the common memory to all the members.

The size of union variable is the size of member with the maximum length. Say for example if a union has different members like int, char and double then instance of such union takes 8 Bytes that is the size of double. All the members share the same common memory.

struct demo
{
 float x;
 short y;
 char ch;
};

struct demo var;

Struct Variable vs union

Here the variable belongs to struct has all the members of struct definition

union demo
{
 float x;
 short y;
 char ch;
};

union demo var;

Union variable

Here the variable belongs to union has common memory to all the members, the size of which is the size of big member float that is 4 Bytes. We can demonstrate this with an example

#include<stdio.h>
struct demo1
{
 float x;
 short y;
 char ch;
};
union demo2
{
 float x;
 short y;
 char ch;
};
int main()
{
 struct demo1 var1;
 union demo2 var2;
 printf("Size of struct variable is %d bytes\n",sizeof(var1));
 printf("Size of union variable is %d bytes\n",sizeof(var2));
 return 0;
}

Output:
Size of struct variable 7 bytes
Size of union variable 4 bytes

Here the struct variable takes 7 Bytes that it has the memory allocation of all members. Where as the union variable takes 4 Bytes that it has common memory to all the members.

Now let us go through another example which demonstrates the same

#include<stdio.h>
union demo
{
 short x;
 char ch[2];
};
void showbits(int);
int main()
{
 union demo a;
 a.x=615;
 printf("a.x=");
 showbits(a.x);
 printf("a.ch[0]=");
 showbits(a.ch[0]);
 printf("a.ch[1]=");
 showbits(a.ch[1]);
 return 0;
}
void showbits(int n)
{
 long bin;
 int i;
 for(bin=0,i=0;n!=0;n=n/2,i++)
   bin=bin+(n%2)*pow(10,i);
 printf("\n%ld",bin);
}

Output:
a.x=1001100111
a.ch[0]=1100111
a.ch[1]=10

Union variable with array

Here the showbits() is a function accepts a number and prints its binary equal. “x” is the member with maximum length hence the union variable takes 2 bytes. Another member ch[2] uses the same memory.

When 615 is assigned to “x” then its binary equal (1001100111) is stored in the memory.
Here ch[0] is 1100111 and ch[1] is 00000010

By this it is confirmed that members of union variable use common memory

#include<stdio.h>
union demo
{
 short x;
 char ch[2];
};
int main()
{
 union demo a;
 a.x=615;
 printf("a.x=%d",a.x);
 printf("\na.ch[0]=%c",a.ch[0]);
 printf("\na.ch[1]=%c",a.ch[1]);
 return 0;
}

Output:
a.x=615
a.ch[0]=g
a.ch[1]=☻

Union variable with array

Here in this example printing the values of members rather bits. Equal character to 01100111 is g (103) and equal character to is 00000010 ☻(2) are being printed.

Only a single member can be used in a union

With the above examples we come to know that, common memory is used by all the members of union, any single member can be used at a time because assigning value to the second member will result overwriting on the first assigned member.

#include<stdio.h>
union num
{
 short x;
 float y;
};
int main()
{
 union num a;
 a.x=4526;
 a.y=123.986712;
 printf("x=%d\n",a.x);
 printf("y=%f\n",a.y);
 return 0;
}

Output
x=-1742
y=123.986710

Here “x” is assigned with 4526 but, printed as -1742 because value assigned to the second member is overwritten on the value assigned to the first member.

Initializing a union variable

We can’t initialize multiple values while declaration of a union variable which results error because only a single member can be assigned at a time.

#include<stdio.h>
union num
{
 short x;
 float y;
};
int main()
{
 union num a={40,12.50};
 printf("x=%d\n",a.x);
 printf("y=%f\n",a.y);
 return 0;
}

Output
Error: Multiple values can’t be initialized

Though we can’t assign multiple values to a union variable, a single value can be assigned and that would be assigned to the first member.

#include<stdio.h>
union num
{
 short x;
 float y;
};
int main()
{
 union num a={12.50};
 printf("x=%d\n",a.x);
 printf("y=%f\n",a.y);
 return 0;
}

Output
x=12
y=0.000000

Here 12.50 is assigned to the first member “x” and the second member is assigned with some unknown value

Union as generic type:

Now you may be confused, then why do we need unions with multiple members if we could only store a single value?

The answer is, we can have a union with different members of different types. At a time we can store any single value but of any member type. So any variable belongs to union is capable to store the data belongs to any type called generic type.

Example:

#include<stdio.h>
union demo
{
 float x;
 int y;
 char z;
};
int main()
{
 union demo a,b,c;
 a.x=234.768956;
 b.y=615;
 c.z='s';
 printf("x=%f",a.x);
 printf("\ny=%d",b.y);
 printf("\nz=%c",c.z);
 return 0;
}

Output:
x=234.768951
y=615
z=s

Here a, b and c are of same union demo type but, used to store float, int and char types by using different members.

Summery:

  1. It is a user defined type looks similar to struct but differs in functionality
  2. It is a heterogeneous collection of members defined with a name.
  3. The definition of union doesn’t allocate the memory allocation of members.
  4. When a variable or an instance of a union is created then a common memory allocation to all the members is allocated.
  5. The size of allocated memory is equal to the size of member which has greater length.
  6. The common memory is used by all of its members.
  7. Any single member can be used at a time.
  8. Union is mostly used to define generic type.

Additional points to remember

  1. A pointer can be created to the union variable
  2. A union variable or the address of union variable can be send as an argument to any function
  3. A union variable or the address of a union variable can be returned from a function
  4. A union can be define as a member to a struct
  5. An array of union variables can be created
  6. An alias to union can be created using typedef

Previous post:

Next post: