Lesson 49 of 60 – Unions in C
82%

Unions in C

A union in C is a user-defined data type that allows different members to share the same memory location. A union can contain members of different data types, but only one member's value should be considered active at a time.

Note: A structure allocates separate storage for its members, while a union uses shared storage for all its members.

1. What is a Union?

A union is a user-defined data type in C where all members share the same memory location.

union Data
{
    int number;
    float price;
    char grade;
};

The union can contain members of different types, but they use the same storage area.

2. Why Use a Union?

Unions are useful when different types of information need to use the same memory area at different times.

  • Saving memory
  • Representing alternative data types
  • Working with hardware-related data
  • Embedded programming
  • Memory-efficient applications
  • Representing variant data

3. Union Syntax

The general syntax for defining a union is:

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

The semicolon after the closing brace is required.

4. Defining a Union

union Data
{
    int number;
    float price;
    char grade;
};

This defines a union type named union Data. It does not automatically create a variable named data.

5. Declaring a Union Variable

After defining the union, a variable can be declared using the union type.

union Data data1;

The variable data1 can use any one of its members at a time.

6. Accessing Union Members

The dot operator . is used to access members of a union variable.

data1.number = 100;

printf("%d", data1.number);

The syntax is similar to accessing structure members.

7. Union Stores One Active Value

All members share the same storage. If you assign a new value through one member, the previously stored representation should no longer be treated as the active value of the union.

union Data data;

data.number = 100;
printf("%d", data.number);

data.price = 25.5f;
printf("%.2f", data.price);

The second assignment uses the same storage for price.

8. Union and Shared Memory

The members of a union share storage. Therefore, the size of a union is sufficient to hold its largest member, subject to implementation-defined alignment and padding.

union Data
{
    int number;
    double value;
    char name[30];
};

The union must provide enough storage for its largest member.

9. Checking Union Size

The sizeof operator can be used to determine the size of a union.

union Data
{
    int number;
    double value;
    char name[30];
};

printf("%zu", sizeof(union Data));

The result is implementation-dependent but must be large enough to hold any member.

10. Union Example with int

#include <stdio.h>

union Data
{
    int number;
    float price;
};

int main()
{
    union Data data;

    data.number = 100;

    printf("Number = %d", data.number);

    return 0;
}

11. Union Example with Float

#include <stdio.h>

union Data
{
    int number;
    float price;
};

int main()
{
    union Data data;

    data.price = 99.50f;

    printf("Price = %.2f", data.price);

    return 0;
}

12. Union with Character Data

union Data
{
    int number;
    float price;
    char grade;
};

union Data data;

data.grade = 'A';

printf("%c", data.grade);

The character member uses the same shared storage as the other members.

13. Union Initialization

A union can be initialized when it is declared.

union Data
{
    int number;
    float price;
};

union Data data = {100};

The first member is initialized by this form.

14. Designated Union Initializer

A designated initializer can specify which member is initialized.

union Data
{
    int number;
    float price;
};

union Data data = {
    .price = 99.50f
};

This initializes the price member.

15. Structure vs Union

Structure Union
Members have separate storage Members share storage
Multiple members can hold values at the same time One member's stored value is normally treated as active at a time
Size generally accounts for all members and padding Size is based primarily on the largest member and alignment
Useful for records Useful for alternative representations

16. Union with Structure

A union can contain a structure as one of its members.

struct Student
{
    int id;
    char name[30];
};

union Data
{
    int number;
    struct Student student;
};

The union can use either the integer member or the structure member.

17. Union Inside a Structure

A structure can contain a union as a member.

union Contact
{
    int phone;
    char email[50];
};

struct Customer
{
    int id;
    union Contact contact;
};

This can represent alternative types of contact information.

18. Accessing a Union Inside a Structure

struct Customer customer;

customer.id = 101;

customer.contact.phone = 987654321;

The union member can be accessed using the dot operator through the structure.

19. Pointer to a Union

A pointer can store the address of a union variable.

union Data data;

union Data *ptr = &data;

ptr->number = 500;

The arrow operator is used to access a union member through a pointer.

20. Passing Union to a Function

A union can be passed to a function by value.

void display(union Data data)
{
    printf("%d", data.number);
}

The function receives a copy of the union object.

21. Passing Union Using a Pointer

A pointer to a union can be passed to a function.

void display(union Data *data)
{
    printf("%d", data->number);
}

Passing a pointer avoids copying the union and allows the function to modify the union when appropriate.

22. typedef with Union

The typedef keyword can create a shorter name for a union type.

typedef union
{
    int number;
    float price;
    char grade;
} Data;

Now we can declare a variable using:

Data data1;

23. Union with an Array Member

A union can contain an array as a member.

union Data
{
    int number;
    char text[30];
};

union Data data;

data.text[0] = 'H';
data.text[1] = 'i';
data.text[2] = '\0';

printf("%s", data.text);

The array uses the union's shared storage.

24. Type-Punning Caution

Because union members share memory, programs sometimes access the stored representation through a different member. However, interpreting an object through a different union member has rules and implementation-defined or unspecified aspects depending on the situation and C standard version.

For beginner programs, use a union by writing and then reading the member that represents the current stored value.

25. Common Mistake: Expecting All Values to Remain Independent

Union members share the same storage, so assigning one member changes the shared memory used by the union.

union Data data;

data.number = 100;
data.price = 50.5f;

Do not expect both assignments to represent two independent stored values as they would in a structure.

26. Common Mistake: Confusing . and ->

Use the dot operator with a union variable and the arrow operator with a pointer to a union.

union Data data;
union Data *ptr = &data;

data.number = 100;
ptr->number = 200;

Using the correct operator makes member access clear and valid.

27. Complete Union Program

#include <stdio.h>

union Data
{
    int number;
    float price;
    char grade;
};

int main()
{
    union Data data;

    data.number = 100;

    printf("Number = %d\n", data.number);

    data.price = 75.50f;

    printf("Price = %.2f\n", data.price);

    data.grade = 'A';

    printf("Grade = %c\n", data.grade);

    printf("Union Size = %zu\n", sizeof(data));

    return 0;
}

This program demonstrates that different members use the same union storage.

28. Practical Variant Data Example

#include <stdio.h>

enum Type
{
    TYPE_INT,
    TYPE_FLOAT
};

union Value
{
    int number;
    float decimal;
};

struct Data
{
    enum Type type;
    union Value value;
};

int main()
{
    struct Data data;

    data.type = TYPE_INT;
    data.value.number = 100;

    if(data.type == TYPE_INT)
    {
        printf("Value = %d", data.value.number);
    }

    return 0;
}

A tag such as an enum can be used to record which union member currently represents the stored value.

29. Practical Uses of Unions

Unions can be useful in:

  • Memory-efficient data structures
  • Embedded systems
  • Hardware programming
  • Protocol and binary data handling
  • Alternative data representations
  • Variant data structures
  • Low-level programming
  • Applications where only one of several values is needed at a time

30. Practice Program

Create a C program that:

  1. Defines a union named EmployeeData.
  2. Adds an integer employee ID.
  3. Adds a floating-point salary.
  4. Adds a character grade.
  5. Creates a union variable.
  6. Stores and displays each member separately.
  7. Displays the size of the union.
  8. Creates a structure containing the union and an additional type indicator.

Observe how all union members share the same memory.

📌 Key Points

  • A union is a user-defined data type.
  • All union members share the same memory location.
  • A union can contain members of different data types.
  • Only one member's stored value should normally be treated as active at a time.
  • The dot operator . accesses a member through a union variable.
  • The arrow operator -> accesses a member through a union pointer.
  • The size of a union is sufficient for its largest member, subject to alignment and implementation details.
  • Structures allocate separate storage for their members, while unions share storage.
  • A union can be placed inside a structure.
  • A structure can also be a member of a union.
  • typedef can provide a shorter name for a union type.
  • Unions are useful when different types need to occupy the same memory at different times.

🧠 Quick Quiz

Question: How do the members of a union use memory?