📚 C Programming Tutorial

C Programming

Learn C programming concepts with simple explanations, examples and practical notes.

← Back to C Programming

Union

What is a union in C?

A union is a user-defined data type in C that allows different members to share the same memory location.

A union can contain members of different data types, such as int, float, and char. However, all its members share the same storage area, so writing to one member can overwrite the value previously stored through another member.

Definition: A union is a user-defined data type in C in which all members share the same memory location, allowing the same memory space to be used for different types of data at different times.

Syntax of a union

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

Example:

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

Explanation:
- union is the keyword used to declare a union type.
- Data is the name of the union type.
- i, f, and ch are its members.
- All three members share the same memory area.

Declaring a union type does not, by itself, create a union variable. We can declare variables separately:

union Data d;

Or declare them along with the definition:

union Data
{
    int i;
    float f;
    char ch;
} d1, d2;

How does a union work?

Consider this union:

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

Unlike a structure, where each member has its own storage, the union members overlap in memory.

Accessing union members using the dot (.) operator

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

Example 1: Basic union program

#include <stdio.h>

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

int main( )
{
    union Data d;

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

    d.f = 25.5f;
    printf("Float value = %.1f\n", d.f);

    d.ch = 'A';
    printf("Character value = %c\n", d.ch);

    return 0;
}

Output:

Integer value = 10
Float value = 25.5
Character value = A

Explanation

  1. d.i = 10; stores an integer in the shared memory.
  2. d.f = 25.5f; stores a float in the same memory, replacing the previously stored representation.
  3. d.ch = 'A'; stores a character in that shared memory.

Each value is printed immediately after it is assigned, while that member holds the intended value.

Important: Do not assume that all three members retain their assigned values simultaneously. After storing a new value through one member, you should generally read that active member rather than expect the earlier member's value to remain intact.

Understanding memory sharing step by step

Consider the following statements:

union Data d;

d.i = 100;
printf("%d\n", d.i);

d.f = 12.5f;
printf("%.1f\n", d.f);

The main idea is one shared storage area, used by different members at different times.

Difference between struct and union

This is one of the most important exam questions.

Feature Structure (struct) Union (union)
Memory allocation Each member has its own storage Members share storage
Member values Members can hold values simultaneously Typically, only the most recently stored member is intended to be read
Size At least enough for all members, plus possible padding At least enough for the largest member, plus possible padding
Memory usage Usually more for the same set of member types Often less when only one member is needed at a time
Member access Dot (.) or arrow (->) Dot (.) or arrow (->)
Typical use Student records, employee records Variant data, memory-constrained applications

Example 2: Structure versus union

#include <stdio.h>

struct Sample
{
    int i;
    float f;
};

union SampleUnion
{
    int i;
    float f;
};

int main( )
{
    struct Sample s;
    union SampleUnion u;

    s.i = 10;
    s.f = 20.5f;

    u.i = 10;
    u.f = 20.5f;

    printf("Structure: %d %.1f\n", s.i, s.f);
    printf("Union: %.1f\n", u.f);

    return 0;
}

Typical output:

Structure: 10 20.5
Union: 20.5

Explanation

  • In s, i and f occupy separate member storage, so both values remain available.
  • In u, assigning u.f after u.i makes the float member the one to read for this example.

The size of struct Sample is commonly 8 bytes on systems where int and float are each 4 bytes, though padding can affect the result. The union is commonly 4 bytes on such systems.

Initializing a union

A union can be initialized when its variable is declared.

Example 3: Initializing the first member

#include <stdio.h>

union Value
{
    int number;
    float decimal;
    char letter;
};

int main( )
{
    union Value v = {25};

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

    return 0;
}

Output:

Number = 25

Here, {25} initializes the first member, number.

Designated initialization

You can explicitly specify which member to initialize:

union Value v = {.decimal = 3.14f};

printf("%.2f\n", v.decimal);

Output:

3.14

The designated initializer makes the intended member clear.

Finding the size of a union using sizeof

The sizeof operator returns the size of a union in bytes.

Example 4: Size of a union

#include <stdio.h>

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

int main( )
{
    printf("Size of int = %zu bytes\n", sizeof(int));
    printf("Size of float = %zu bytes\n", sizeof(float));
    printf("Size of char = %zu bytes\n", sizeof(char));
    printf("Size of union = %zu bytes\n", sizeof(union Data));

    return 0;
}

On a common system where int and float are 4 bytes each, the output is:

Size of int = 4 bytes
Size of float = 4 bytes
Size of char = 1 bytes
Size of union = 4 bytes

The union's size is not necessarily the sum of its member sizes. It must be large enough for the largest member and may include padding.

Array of unions

An array can contain union variables. Each element has enough storage for the union type.

Example 5: Array of unions

#include <stdio.h>

union Item
{
    int number;
    float price;
};

int main( )
{
    union Item items[3];

    items[0].number = 10;
    items[1].price = 25.5f;
    items[2].number = 30;

    printf("Item 1 = %d\n", items[0].number);
    printf("Item 2 = %.1f\n", items[1].price);
    printf("Item 3 = %d\n", items[2].number);

    return 0;
}

Output:

Item 1 = 10
Item 2 = 25.5
Item 3 = 30

Each array element has its own shared storage. Therefore, assigning a member in items[1] does not overwrite the storage belonging to items[0].

Pointer to a union

A pointer can store the address of a union variable. Use the arrow (->) operator to access a member through a pointer.

Example 6: Union pointer

#include <stdio.h>

union Data
{
    int number;
    float value;
};

int main( )
{
    union Data d;
    union Data *ptr = &d;

    ptr->number = 50;

    printf("Number = %d\n", ptr->number);

    ptr->value = 8.5f;

    printf("Value = %.1f\n", ptr->value);

    return 0;
}

Output:

Number = 50
Value = 8.5

Explanation

  • union Data *ptr declares a pointer to a union.
  • ptr = &d stores the address of d.
  • ptr->number accesses the integer member.
  • ptr->value accesses the float member.

The expression ptr->number is equivalent to (*ptr).number.

Where are unions used?

Unions are useful when a program needs to represent one of several possible kinds of data while reusing memory.

  1. Embedded systems: Memory can be limited, so sharing storage between alternative data representations can be useful.
  2. Protocols and packet processing: A field may represent different kinds of values depending on the packet type.
  3. Compilers and interpreters: A value may represent an integer, a floating-point number, or another permitted data form.
  4. Hardware and device software: Different interpretations of the same storage may be needed when working with device data.

Quick revision

Question Answer
Which keyword declares a union? union
Do all members share memory? Yes
Which operator accesses a member directly? .
Which operator accesses a member through a pointer? ->
Does a union's size equal the sum of member sizes? No
Can all members independently retain their values? No
Can a union contain different data types? Yes