Skip to content
StudyFame

Unions in C

A union looks almost exactly like a structure, but behaves very differently. In a structure, every member has its own memory. In a union, all members share the same memory, so only one of them holds a valid value at a time.

In this lesson you will declare unions, see why their size equals the largest member, watch one member overwrite another, and use a tagged union to store "one of several kinds" of data safely.

What You Will Learn

  • What a union is.
  • How to declare a union and access members.
  • Why all members share one memory location.
  • How the size of a union is decided.
  • Why only the last-written member is valid.
  • How to use a tagged union.

What is a Union in C?

Exam definition: A union is a user-defined data type in which all members share the same memory location. Its size equals the size of its largest member, and only one member can hold a meaningful value at a time.

Memory trick: A union is a single hostel room that can be given to only one guest at a time. The room must be big enough for the biggest guest. When a new guest checks in, the old guest's things are thrown out.

Syntax of a Union

union data                  /* keyword union instead of struct */
{
    int   i;
    float f;
    char  str[20];
};

union data d;               /* declare */
d.i = 10;                   /* access with dot, like a structure */
union data *p = &d;
p->f = 2.5f;                /* arrow through a pointer */

union data e = {42};        /* initializer sets the FIRST member only */

How Union Memory Works

union data { int i; float f; char str[20]; };

Byte:   0   1   2   3   4   5  ...  19
       [ i (4 bytes) ]
       [ f (4 bytes) ]
       [        str (20 bytes)          ]
All members START at the same address.  sizeof(union data) = 20

Compare: struct with the same members = 4 + 4 + 20 = 28 bytes
  • Every member begins at byte 0 of the union.
  • Size = size of the largest member (possibly rounded up for alignment).
  • Writing one member overwrites the bytes of the others.

Example 1: Size of a Union and Overwriting Members

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

union data
{
    int i;
    float f;
    char str[20];
};

struct sdata
{
    int i;
    float f;
    char str[20];
};

int main(void)
{
    union data d;

    printf("sizeof(union data)  = %zu\n", sizeof(union data));
    printf("sizeof(struct sdata)= %zu\n", sizeof(struct sdata));

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

    d.f = 3.5f;                     /* overwrites the same bytes */
    printf("d.f   = %.1f\n", d.f);

    strcpy(d.str, "Hello");         /* overwrites again */
    printf("d.str = %s\n", d.str);

    printf("Same address? %s\n",
           (void *) &d.i == (void *) &d.f && (void *) &d.f == (void *) d.str ? "yes" : "no");

    return 0;
}

Output

sizeof(union data)  = 20
sizeof(struct sdata)= 28
d.i   = 25
d.f   = 3.5
d.str = Hello
Same address? yes

Code Explanation

  1. The union is 20 bytes (its biggest member, str). The structure with the same members needs 28.
  2. Each value is printed right after it is written, so it is valid.
  3. After d.f = 3.5f, the old d.i is gone: the same 4 bytes now hold a float.
  4. After strcpy, both i and f are overwritten by the characters of "Hello". Reading d.i now would give a meaningless number.
  5. The address check proves all three members start at the same address.

Why Use a Union?

  • Save memory when a variable holds only one of several types at a time (very useful in embedded systems with small RAM).
  • Variant data: a value that can be an int or a float or a string, like a cell in a spreadsheet.
  • Looking at raw bytes of a value (for example, network or hardware programming), though the result depends on the machine.

To know which member is currently valid, programs store a separate tag next to the union. This pattern is called a tagged union.

Example 2: Tagged Union for Different Shapes

#include <stdio.h>

#define CIRCLE    1
#define RECTANGLE 2
#define SQUARE    3

struct shape
{
    int kind;                       /* the tag: which member is valid */
    union
    {
        float radius;               /* used when kind == CIRCLE    */
        struct { float l, b; } rect;/* used when kind == RECTANGLE */
        float side;                 /* used when kind == SQUARE    */
    } dim;
};

float area(const struct shape *s)
{
    switch (s->kind)
    {
        case CIRCLE:    return 3.14f * s->dim.radius * s->dim.radius;
        case RECTANGLE: return s->dim.rect.l * s->dim.rect.b;
        case SQUARE:    return s->dim.side * s->dim.side;
    }
    return 0;
}

int main(void)
{
    struct shape list[3];
    const char *names[] = {"", "Circle", "Rectangle", "Square"};
    int i;

    list[0].kind = CIRCLE;     list[0].dim.radius = 2;
    list[1].kind = RECTANGLE;  list[1].dim.rect.l = 4; list[1].dim.rect.b = 3;
    list[2].kind = SQUARE;     list[2].dim.side = 5;

    for (i = 0; i < 3; i++)
        printf("%-9s area = %.2f\n", names[list[i].kind], area(&list[i]));

    printf("sizeof(struct shape) = %zu bytes\n", sizeof(struct shape));
    return 0;
}

Output

Circle    area = 12.56
Rectangle area = 12.00
Square    area = 25.00
sizeof(struct shape) = 12 bytes
  • kind records which union member was filled. area checks it before reading.
  • The union is only as big as its largest member (the rectangle's 8 bytes), so each shape takes 4 + 8 = 12 bytes instead of 4 + 4 + 8 + 4 = 20.
  • The union here has no tag name; it's used only inside struct shape, through the member name dim.

Important Points to Remember

  • Keyword union; members accessed with . and -> like structures.
  • All members share one memory block starting at the same address.
  • Size = largest member (plus any alignment padding).
  • Only the last-written member is valid.
  • An initializer sets the first member (or use {.f = 2.5f}).
  • Use a tag variable to remember which member is active.

Common Mistakes Beginners Make

MistakeWhat happensFix
Storing all members and reading them allOnly the last one is correct; others are garbageUse one member at a time
Thinking sizeof(union) = sum of membersWrong exam answerIt's the largest member
union data d = {3.5f}; expecting fGoes into i (first member) as 3union data d = {.f = 3.5f};
No record of which member is activeReading the wrong typeAdd a tag (tagged union)
Using a union where all fields are needed togetherData overwrittenUse a structure

Unions in C Practice Questions

  1. Define a union.
  2. What is the size of union u { char c; double d; int a[3]; }; on a typical 64-bit system?
  3. After u.c = 'A'; u.d = 9.5;, which member is valid?
  4. What is a tagged union?
  5. Give two uses of unions.
Show answers
  1. A user-defined type whose members share the same memory; its size is that of the largest member and only one member is valid at a time.
  2. 16 bytes: the largest member is int a[3] (12 bytes), rounded up to a multiple of 8 because of the double's alignment.
  3. Only u.d.
  4. A structure that holds a union plus a tag field recording which union member is currently stored.
  5. Saving memory when only one of several values is needed at a time; storing variant data (int or float or string); viewing raw bytes.

Coding Exercise

Create a tagged union struct value that can hold an int, a float or a string (up to 15 chars). Store one of each in an array and print them according to their tag.

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

struct value
{
    char type;                 /* 'i', 'f' or 's' */
    union
    {
        int i;
        float f;
        char s[16];
    } v;
};

int main(void)
{
    struct value list[3];
    int k;

    list[0].type = 'i'; list[0].v.i = 42;
    list[1].type = 'f'; list[1].v.f = 3.75f;
    list[2].type = 's'; strcpy(list[2].v.s, "C rocks");

    for (k = 0; k < 3; k++)
    {
        if (list[k].type == 'i')      printf("int   : %d\n", list[k].v.i);
        else if (list[k].type == 'f') printf("float : %.2f\n", list[k].v.f);
        else                          printf("string: %s\n", list[k].v.s);
    }
    return 0;
}
int   : 42
float : 3.75
string: C rocks

Quick Quiz: Unions in C (MCQ)

  1. In a union, members:

    A) Have separate memory   B) Share the same memory   C) Are all pointers   D) Must be the same type

  2. Size of union { int a; char b[10]; float c; } (int = float = 4):

    A) 18   B) 12   C) 4   D) 10

  3. How many members of a union hold a valid value at a time?

    A) All   B) One   C) Two   D) None

  4. union u x = {5}; initializes:

    A) All members   B) The first member   C) The last member   D) The largest member

  5. Keyword to declare a union:

    A) struct   B) union   C) enum   D) typedef

Show answers
  1. B: share the same memory.
  2. B: 12. The largest member is 10 bytes, rounded up to a multiple of 4 for int alignment.
  3. B: one.
  4. B: the first member.
  5. B: union.

Quick Revision for Exams and Interviews

Read this before your exam. The highlighted words are the answer.

Must-remember facts

UnionMembers share one memory location
SizeLargest member (+ alignment)
Valid memberOnly the last written
InitializerSets the first member
Access. and ->, like structures
Tagged unionUnion + tag saying which member is active

Frequently asked questions

What is a union in C?
A user-defined type whose members share the same memory, so only one member is valid at a time.
How is the size of a union calculated?
It equals the size of its largest member, rounded up for alignment.
When should you use a union?
When a variable holds only one of several types at a time and you want to save memory.

Remember

  • Union = one hostel room, one guest at a time.
  • Size of the room = the biggest guest.

Next Topic

Next lesson: Structure vs Union in C. You will compare structures and unions side by side, a classic exam question.