The ‘union’ Keyword in C Programming

C Programming @ Freshers.in

In the world of C programming, the ‘union’ keyword is a versatile tool for optimizing memory usage and working with multiple data types efficiently. This comprehensive article aims to elucidate the ‘union’ keyword, explaining its purpose, usage, and providing real-world examples with outputs. By the end, you’ll have a deep understanding of how ‘union’ empowers you to manage data structures in your C code effectively.

The Purpose of the ‘union’ Keyword

The ‘union’ keyword in C is used to create data structures that can hold different data types in the same memory location. Unlike ‘struct,’ which allocates memory for all its members, a ‘union’ allocates memory only for the largest member, enabling efficient memory usage.

Usage of the ‘union’ Keyword

To use ‘union,’ you define a union type with the ‘union’ keyword, followed by a user-defined name for the union. Inside the union, you specify the members with their respective data types. All members share the same memory location, but you can only access one member at a time.

Example 1: Creating a Union with Different Data Types

Let’s create a union that can store either an integer or a floating-point number. We’ll demonstrate how to access and use both types within the union:

#include <stdio.h>
// Define a union named 'NumberUnion'
union NumberUnion {
    int integerValue;
    float floatValue;
};
int main() {
    union NumberUnion num;
    // Store an integer and access it
    num.integerValue = 42;
    printf("Stored Integer: %d\n", num.integerValue);
    // Store a float and access it
    num.floatValue = 3.14;
    printf("Stored Float: %.2f\n", num.floatValue);
    return 0;
}

In this example, we define a ‘NumberUnion’ union capable of holding both integers and floating-point numbers.

Output:

Stored Integer: 42
Stored Float: 3.14

Example 2: Union with Struct Inside

Unions can also contain structures, enabling even more complex data structures. Let’s create a union that can hold either a date (day, month, year) or a single floating-point value:

#include <stdio.h>
// Define a structure for a date
struct Date {
    int day;
    int month;
    int year;
};
// Define a union that can hold a date or a float
union DataUnion {
    struct Date dateValue;
    float floatValue;
};
int main() {
    union DataUnion data;
    // Store a date and access it
    data.dateValue.day = 15;
    data.dateValue.month = 7;
    data.dateValue.year = 2023;
    printf("Stored Date: %02d/%02d/%04d\n", data.dateValue.month, data.dateValue.day, data.dateValue.year);
    // Store a float and access it
    data.floatValue = 3.1416;
    printf("Stored Float: %.4f\n", data.floatValue);
    return 0;
}

In this example, we define a ‘DataUnion’ union that can hold either a ‘Date’ structure or a floating-point number.

Output:

Stored Date: 07/15/2023
Stored Float: 3.1416
Author: user