Unions in C programming language, need and use

Unions in C are user defined data type similar to structures. Union allows to define multiple members of different type at single location. In this article I will explain what is union, need of union, how to declare, define and access unions in C programming language.

We use unions to define a new data type, similar to structures in C. Its definition, use and access are almost similar to structures. If I say its similar to structure, then you may think why in the world do we need it then. Hence, let us first explore the real world need of a union type.

Need of unions in C programming language

Let us take an example to understand the real world use of union. Suppose we have a requirement to create a new type color to store color of an object. It should accept color input in all formats. We end up with following structure definition.

struct color 
{
    struct color_rgb  rgb;   // rgb color value
    struct color_rgba rgba;  // rgba color value
    unsigned int  value;     // hexadecimal or integer value
    char name[20];           // Unique string representing color name
};

The above structure approach has one big problem. At any time one object will store one color value. Hence, you will either use rgb, rgba or value or name to store color. In no case you will you two different formats of color. But, still we are wasting memory for all members of color structure unknowingly.

To overcome such type of real world problems we use union. Unlike structures union occupies single memory location to store all its members. So, unions are helpful when you want to store value in single member from a set of members.
Size of union is defined according to size of largest member data type. For example, if there are three members (char, short and int) in union, the size of union will be sizeof(int).

How to define union?

We use union keyword to define unions in C language. Its syntax is similar to structure definition.

Syntax of union definition

union union_name
{
    union_member1;
    union_member2;
    ...
    ...
    ...
    union_member_N;
};

Example of union definition

union color 
{
    struct color_rgb  rgb;   // rgb color value
    struct color_rgba rgba;  // rgba color value
    unsigned int  value;     // hexadecimal or integer value
    char name[20];           // Unique string representing color name
};

Here,

  • union is a C keyword used to define a union.
  • color is an identifier/name of union.
  • rgb, rgba, value and name are union members.

The above union definition will occupy 20 bytes in memory. Since size of largest data type is 20 i.e. the character array of name.

How to declare union variable?

Union variable declaration follows same structure definition syntax. You can declare a union variable/object in two ways.

  1. Along with union definition
  2. After union definition

Declaration along with union definition

You can declare a union variable right after union definition. The union definition must be followed by union variable declaration.

Example:

union color 
{
    struct color_rgb  rgb;    // color in rgb
    struct color_rgba rgba;   // color in rgba
    unsigned int value;       // hexadecimal or decimal color value
    char name[20];            // unique string color name
} console_color;

Declaration after union definition

This approach to declare union variable sets you free to declare union variable anywhere in program. You are not only restricted to declare union along with its definition.

Example:

union color 
{
    struct color_rgb  rgb;    // color in rgb
    struct color_rgba rgba;   // color in rgba
    unsigned int value;       // hexadecimal or decimal color value
    char name[20];            // unique string color name
};

// Declare color type variable
union color console_color;

How to access union members?

Similar to structures, C supports two operators to access union members using union variable.

Dot/period operator in C

Dot/period operator is also known as member access operator in C programming. We use dot operator to access union members.

Syntax:

union_variable.member_name;

Example:

console_color.value = 999;

Arrow operator in C

We use arrow operator to access members of a pointer to structure or union.

Syntax:

union_pointer->member_name;

Example:

console_color->value = 999;

Example program to declare, define and access unions

Let us use our color union example. In this example I will declare a color union and take input from user and print the value on console.

/**
 * C program to declare, define and access union.
 */

#include <stdio.h>

// Rgb color structure declaration
struct color_rgb
{
    unsigned char r;    // Red value
    unsigned char g;    // Green value
    unsigned char b;    // Blue value
};

// Rgba color structure declaration
struct color_rgba
{
    unsigned char r;    // Red value
    unsigned char g;    // Green value
    unsigned char b;    // Blue value
    float         a;    // Opacity value
};



/**
 * Union definition to store color
 */
union color 
{
    struct color_rgb  rgb;      // rgb color value
    struct color_rgba rgba;     // rgba color value
    
    unsigned int value;         // integer color value
    char name[20];              // String name of color
};



int main()
{
    // Declare color variable 
    union color console_color;

    // Print size of union variable
    printf("Size of color variable = %d\n\n", sizeof(console_color));

    printf("Enter space separated rgb color value: ");
    scanf("%d %d %d", &console_color.rgb.r, 
                      &console_color.rgb.g, 
                      &console_color.rgb.b);
    printf("Color in rgb format: %d %d %d\n\n", 
                      console_color.rgb.r, 
                      console_color.rgb.g, 
                      console_color.rgb.b);
    

    printf("Enter space separated rgba color value: ");
    scanf("%d %d %d %f", &console_color.rgba.r, 
                         &console_color.rgba.g, 
                         &console_color.rgba.b, 
                         &console_color.rgba.a);
    printf("Color in rgba format: %d %d %d %.2f\n\n", 
                         console_color.rgba.r, 
                         console_color.rgba.g, 
                         console_color.rgba.b, 
                         console_color.rgba.a);


    printf("Enter integer color value: ");
    scanf("%d", &console_color.value);
    printf("Color in integer format: %d\n\n", console_color.value);


    printf("Enter string color value: ");
    getchar(); // Eat extra new line character
    gets(console_color.name);
    printf("Color in string format: %s\n\n", console_color.name);


    return 0;
}

Output

Size of color variable = 20

Enter space separated rgb color value: 11 84 130
Color in rgb format: 11 84 130

Enter space separated rgba color value: 19 147 49 0.45
Color in rgba format: 19 147 49 0.45

Enter integer color value: 999
Color in integer format: 999

Enter string color value: black
Color in string format: black

Happy coding 😉