C Program to Demonstrate Union in C

In this tutorial, we will learn how unions work in C programming. A union allows you to store different data types in the same memory location.

Concept Overview

A union is similar to a structure, but with one key difference — all members of a union share the same memory. This means that assigning a value to one member may affect the others.

Program

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

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

int main() {
    union Data data;

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

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

    strcpy(data.str, "C Programming");
    printf("data.str: %s\n", data.str);

    // Showing effect of union: previous values may be overwritten
    printf("data.i: %d\n", data.i);
    printf("data.f: %f\n", data.f);
    printf("data.str: %s\n", data.str);

    return 0;
}

Output

data.i: 10
data.f: 20.500000
data.str: C Programming
data.i: 1917853763
data.f: 4122360580327794860452759994368.000000
data.str: C Programming

Explanation

  • `union Data` – Defines a union with an integer, float, and character array.
  • `data.i = 10;` – Assigns an integer value to the union.
  • `data.f = 20.5;` – Stores a float value in the same memory location (overwrites previous data).
  • `strcpy(data.str, "C Programming");` – Copies a string to the same memory space.
  • After assigning the string, previous values (`i` and `f`) become corrupted because all members share memory.