Skip to main content

Simple Union Example in C

2 min read Updated May 29, 2025
Share:
On this page (10sections)

About this program

This is an example program in c structure and union programs. Read the concept first: C Structures, then study the code and output below.

Definition

  • A union is like a struct, but all members share the same memory location.
  • Only one member can hold a valid value at a time.
  • Unions are useful for saving memory or representing data that can be one of several types.

Syntax

union tag_name {
    type member1;
    type member2;
};

Simple Union Example Program

#include <stdio.h>

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

int main(void) {
    union Data data;

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

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

    /* After writing f, i is no longer valid */
    return 0;
}

Sample Output

data.i = 10
data.f = 3.14

Union vs Structure

FeatureStructureUnion
MemoryEach member has its own spaceAll members share one space
SizeSum of members (with padding)Size of largest member
UsageStore all fields togetherStore one field at a time

Practical Example — Integer or Float

#include <stdio.h>

union Value {
    int asInt;
    float asFloat;
};

int main(void) {
    union Value v;
    v.asInt = 42;
    printf("As integer: %d\n", v.asInt);

    v.asFloat = 3.5f;
    printf("As float: %.1f\n", v.asFloat);
    return 0;
}

Sample Output

As integer: 42
As float: 3.5

Detailed About Union Concepts

See the full tutorial: C Unions.

Learn the concept first, then study the code:

Related Tutorials

Search tutorials