0
0
CHow-ToBeginner · 3 min read

How to Declare Union in C: Syntax and Examples

In C, you declare a union using the union keyword followed by a name and a block of member variables inside braces. Each member shares the same memory location, so only one member can hold a value at a time.
📐

Syntax

A union is declared with the keyword union, followed by the union name and a block containing its members. Each member can be of different types, but they share the same memory space.

  • union: keyword to declare a union
  • Name: identifier for the union type
  • Members: variables inside braces that share memory
c
union UnionName {
    type1 member1;
    type2 member2;
    type3 member3;
};
💻

Example

This example shows how to declare a union with an integer and a float. It assigns a value to one member and prints it, then assigns a value to the other member and prints it. Notice how the value changes because both members share the same memory.

c
#include <stdio.h>

union Number {
    int i;
    float f;
};

int main() {
    union Number num;

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

    num.f = 220.5f;
    printf("num.f = %.2f\n", num.f);

    // After assigning to num.f, num.i value changes
    printf("num.i after assigning num.f = %d\n", num.i);

    return 0;
}
Output
num.i = 10 num.f = 220.50 num.i after assigning num.f = 1120403456
⚠️

Common Pitfalls

One common mistake is assuming all members of a union hold their values independently. In reality, all members share the same memory, so changing one member overwrites the others. Another pitfall is not initializing the union before reading a member, which can lead to undefined behavior.

Wrong way example:

union Data {
    int x;
    float y;
};

union Data d;
printf("d.y = %f\n", d.y);  // Reading uninitialized member

Right way example:

union Data d;
d.x = 5;
printf("d.x = %d\n", d.x);
📊

Quick Reference

  • Use union to save memory when only one of several variables is needed at a time.
  • Only one member can hold a valid value at any moment.
  • Accessing a member different from the last assigned one leads to unpredictable results.
  • Unions can be anonymous or named.

Key Takeaways

Declare a union with the union keyword followed by member variables inside braces.
All union members share the same memory location; only one member holds a valid value at a time.
Assigning a value to one member overwrites the others.
Always initialize a union member before reading it to avoid undefined behavior.
Use unions to save memory when you need to store different types but only one at a time.