Union in C Programming

Union in C Programming

A union in C programming is a user defined data type which may hold members of different sizes and type. Union uses a single memory location to hold more than one variables. However, only one of its members can be accessed at a time and all other members will contain garbage values.

The memory required to store a union variable is the memory required for the largest element of the union. We can use pointers to unions and can access members using arrow operator (->).

Table of Contents

We can use the unions in the following locations.

  1. Share a single memory location for a variable and use the same location for another variable of different data type.
  2. Use it if you want to use, for example, a long variable as two short type variables.
  3. We don’t know what type of data is to be passed to a function, and you pass union which contains all the possible data types.

So, how we can define and declare and initialize a union in a C Program?

How to Define a Union in C?

Union can be defined by the keyword union followed by list of member variables contained in curly braces.

union Employee{
 int age;
 long salary;
};

Here we have defined a union with the name union_name and it has two members i.e. age of type int and salary of type long.

How to Declare a Union in C?

We can declare the union in various ways. By taking the above example we can declare the above defined union as.

union Employee{
 int age;
 long salary;
} employee;

So employee will be the variable of type Employee. We can also declare the above union as: Employee employee;

How to Initialize a Union in C?

We can initialize the union in various ways. For example

union Employee{
 int age;
 long salary;
} employee={20000};

or we can initialize it as

employee.age= 30;
employee.salary=20000;

Normally when we declare the union it is allocated the memory that its biggest member can occupy. So here in our example employee will occupy the memory which a long type variable can occupy.

Similarly union values can be accessed via pointer variables.

union Employee{
 int age;
 long salary;
} *employee;

(*employee).age;
// or;
employee->age;

How to Access Members of a Union?

You can access members of a union using the dot (.) operator, just like you would with structures in C. However, since all members of a union share the same memory space, you can only access one member at a time. Here’s a simple example:

#include <stdio.h>

// Define a union
union MyUnion {
    int intValue;
    float floatValue;
    char stringValue[10];
};

int main() {
    // Declare a union variable
    union MyUnion myUnion;

    // Access and modify members of the union
    myUnion.intValue = 42;
    printf("Integer value: %d\n", myUnion.intValue);

    myUnion.floatValue = 3.14;
    printf("Float value: %f\n", myUnion.floatValue);

    // Accessing char array
    strcpy(myUnion.stringValue, "Hello");
    printf("String value: %s\n", myUnion.stringValue);

    return 0;
}

In this example, the MyUnion union has three members: an integer (intValue), a float (floatValue), and a character array (stringValue). You can access and modify these members using the dot operator based on the type of data you want to work with. Note that changing the value of one member will affect the other members because they share the same memory space.

Working with Array of Union

If you want to create an array of unions and work with them, you can define an array where each element is a union. Each union element can hold different types of data. Here’s an example:

#include <stdio.h>
#include <string.h>

// Define a union with different types
union Data {
    int intValue;
    float floatValue;
    char stringValue[20];
};

// Define a struct to hold a union
struct UnionArrayElement {
    int dataType; // 1 for int, 2 for float, 3 for string
    union Data data;
};

int main() {
    // Define an array of unions
    struct UnionArrayElement myUnionArray[5];

    // Populate the array with different types of data
    myUnionArray[0].dataType = 1;
    myUnionArray[0].data.intValue = 42;

    myUnionArray[1].dataType = 2;
    myUnionArray[1].data.floatValue = 3.14;

    myUnionArray[2].dataType = 3;
    strcpy(myUnionArray[2].data.stringValue, "Hello");

    // Access and print the data in the array
    for (int i = 0; i < 3; ++i) {
        switch (myUnionArray[i].dataType) {
            case 1:
                printf("Integer value: %d\n", myUnionArray[i].data.intValue);
                break;
            case 2:
                printf("Float value: %f\n", myUnionArray[i].data.floatValue);
                break;
            case 3:
                printf("String value: %s\n", myUnionArray[i].data.stringValue);
                break;
            default:
                printf("Unknown data type\n");
        }
    }

    return 0;
}

In this example, the Data union has three members: an integer (intValue), a float (floatValue), and a character array (stringValue). The UnionArrayElement struct contains an integer dataType to indicate the type of data stored in the union.

The program initializes an array of UnionArrayElement and populates it with different types of data. The switch statement is then used to determine the data type of each element in the array and print the corresponding values.

What are the Uses on Union Type?

The important use of a union is allowing access to a common location by different data types. For example hardware input and output access, bit-field and word sharing, or type punning. Unions can also provide low-level polymorphism in C++.

Unions are useful when you need to store different types of data in a compact manner. Since all members of a union share the same memory space, unions can be more memory-efficient than structures when you only need to use one member at a time.

Unions can be useful for bit-level manipulation and operations. By accessing the individual bits within a union member, you can perform bitwise operations on the data.

M. Saqib: Saqib is Master-level Senior Software Engineer with over 14 years of experience in designing and developing large-scale software and web applications. He has more than eight years experience of leading software development teams. Saqib provides consultancy to develop software systems and web services for Fortune 500 companies. He has hands-on experience in C/C++ Java, JavaScript, PHP and .NET Technologies. Saqib owns and write contents on mycplus.com since 2004.
Related Post