Union in C language

 

Union in C Language

Introduction

In the C programming language, a union is a user-defined data type that allows storing different types of data in the same memory location. It is similar to a structure, but the key difference is how memory is allocated. In a structure, each member has its own separate memory location, whereas in a union, all members share the same memory space.

Unions are mainly used when a program needs to work with multiple data types but only one value is required at a time. This helps in saving memory, which is especially useful in embedded systems, low-level programming, and systems programming.

The union keyword is used to declare a union in C. Just like structures, unions can contain variables of different data types such as integers, floats, characters, and arrays.


Definition of Union

A union is a special data type in C that allows storing different data types in the same memory location, but only one member can contain a value at any given time.

Syntax of Union

union union_name
{
    data_type member1;
    data_type member2;
    data_type member3;
};

Example

union Data
{
    int i;
    float f;
    char c;
};

Here, the union Data contains three members:

  • integer i
  • float f
  • character c

All these variables share the same memory location.


Declaring Union Variables

Union variables can be declared in several ways.

1. Declaration with union definition

union Data
{
    int i;
    float f;
    char c;
} data1, data2;

Here data1 and data2 are union variables.


2. Declaration after union definition

union Data
{
    int i;
    float f;
    char c;
};

union Data data1;

3. Anonymous union declaration

union
{
    int i;
    float f;
} data;

Here the union has no name.


Accessing Union Members

Union members are accessed using the dot (.) operator, just like structures.

Example Program

#include <stdio.h>

union Data
{
    int i;
    float f;
    char c;
};

int main()
{
    union Data data;

    data.i = 10;
    printf("Integer: %d\n", data.i);

    data.f = 3.5;
    printf("Float: %f\n", data.f);

    data.c = 'A';
    printf("Character: %c\n", data.c);

    return 0;
}

Output Explanation

When a new value is assigned to a union member, it overwrites the previous value, because all members share the same memory location.


Memory Allocation in Union

The memory size of a union is determined by the largest member in the union.

Example

union Data
{
    int i;      // 4 bytes
    float f;    // 4 bytes
    char c;     // 1 byte
};

Here the largest member is int or float (4 bytes), so the size of the union will be 4 bytes.

Program to Check Union Size

#include <stdio.h>

union Data
{
    int i;
    float f;
    char c;
};

int main()
{
    union Data data;
    printf("Size of union: %lu", sizeof(data));
    return 0;
}

Output will generally be:

Size of union: 4

Union vs Structure

Many beginners confuse unions with structures. Although their syntax looks similar, they behave differently.

Feature Structure Union
Memory allocation Each member has separate memory All members share same memory
Total size Sum of all members Size of largest member
Simultaneous use All members can store values at the same time Only one member can store value at a time
Keyword struct union

Example

struct Test
{
    int a;
    float b;
    char c;
};

union Test2
{
    int a;
    float b;
    char c;
};
  • sizeof(struct Test) ≈ 9 or more bytes (depending on padding)
  • sizeof(union Test2) = 4 bytes

Practical Example of Union

Consider a program that stores different types of data but only one is needed at a time.

#include <stdio.h>

union Student
{
    int roll;
    float marks;
};

int main()
{
    union Student s;

    s.roll = 25;
    printf("Roll Number: %d\n", s.roll);

    s.marks = 89.5;
    printf("Marks: %.2f\n", s.marks);

    return 0;
}

Here the same memory location stores roll number first and marks later.


Union with Structures

Unions can also be used inside structures to create complex data types.

Example

#include <stdio.h>

struct Employee
{
    int id;
    char name[20];

    union Salary
    {
        int hourly;
        int monthly;
    } sal;
};

int main()
{
    struct Employee e1;

    e1.id = 101;
    e1.sal.monthly = 30000;

    printf("Employee ID: %d\n", e1.id);
    printf("Monthly Salary: %d\n", e1.sal.monthly);

    return 0;
}

This is useful when employees can have different salary types.


Union Initialization

Union variables can be initialized during declaration.

Example

union Data
{
    int i;
    float f;
};

union Data data = {10};

Only the first member is initialized by default.


Applications of Union

Unions are useful in various programming situations:

1. Memory Optimization

Unions help reduce memory usage when different variables are used at different times.

2. Embedded Systems

In embedded programming, memory is limited, so unions are widely used.

3. Hardware Register Access

Unions are used to represent hardware registers where multiple data interpretations are needed.

4. Variant Data Storage

Unions allow storing different types of data using the same memory location.

5. Networking and Protocol Design

Unions are useful when decoding packets where the data format may vary.


Advantages of Union

  1. Memory Efficient

    • Saves memory by sharing the same storage location.
  2. Useful in Low-Level Programming

    • Used in device drivers and embedded systems.
  3. Flexible Data Representation

    • Allows interpreting the same memory in multiple ways.
  4. Useful for Variant Data

    • Different types of data can be stored using one variable.

Disadvantages of Union

  1. Data Overwriting

    • Assigning a new value overwrites the previous one.
  2. Only One Member Active

    • Only one member can store a value at a time.
  3. Programming Complexity

    • Can lead to confusion and bugs if used improperly.
  4. Type Safety Issues

    • The compiler does not always prevent misuse.

Difference Between Union and Enumeration

Feature Union Enumeration
Purpose Store different data types Define named integer constants
Memory Shared memory No memory sharing
Keyword union enum

Example Showing Overwriting Behavior

#include <stdio.h>

union Example
{
    int x;
    float y;
};

int main()
{
    union Example e;

    e.x = 10;
    printf("x = %d\n", e.x);

    e.y = 5.5;
    printf("y = %f\n", e.y);

    printf("x after assigning y = %d\n", e.x);

    return 0;
}

This program shows that assigning y changes the stored value and affects x.


Real-Life Analogy of Union

A union can be compared to a single container used for different items but only one item at a time.

For example, a USB drive can store:

  • documents
  • images
  • videos

But at any given time, the same memory space is reused for different data.

Similarly, in a union, one memory location stores different types of values but only one at a time.


Important Points About Union



  1. Union is a user-defined data type.
  2. Declared using the union keyword.
  3. All members share the same memory location.
  4. Size equals the largest member.
  5. Only one member can hold a value at a time.
  6. Members are accessed using the dot operator.
  7. Mostly used in memory-critical applications.

Conclusion

A union in C language is an important feature that allows multiple variables of different data types to share the same memory location. Unlike structures, unions allocate memory equal to the largest member and allow only one member to store data at a time. This makes unions extremely useful for memory optimization and efficient data management.

Unions are commonly used in embedded systems, hardware programming, networking, and system-level programming, where efficient memory usage is crucial. However, programmers must be careful while using unions because assigning a value to one member overwrites the values of other members.

Understanding unions helps programmers design efficient and optimized programs, especially when working with limited memory environments.

Comments

Popular Posts