C Programming

⌘K
  1. Home
  2. Docs
  3. C Programming
  4. Structure and Union
  5. Introduction to Union

Introduction to Union

A union in C is a user-defined data type, similar to a structure, but with a key difference: all members of a union share the same memory location.

  • This means that only one member can hold a value at a time.
  • Unions allow efficient use of memory by storing different types of data in the same memory space.

Use Cases of Unions:

  • Used in embedded systems where memory is limited.
  • Useful for applications like interpreters, parsers, or hardware registers, where data types vary but use the same memory.
  • Helps in type conversions and data management.

Syntax of Union:

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

Example:

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

Memory Allocation:

  • In a structure, memory is allocated for each member separately, so total memory = sum of all members.
  • In a union, memory is allocated only for the largest member. All other members share this memory.
  • Like structures, you use the dot (.) operator with a union variable:
union Data d1;
d1.i = 10;

Example Program:

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

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

int main() {
    union Data data;

    // Assign and print integer
    data.i = 10;
    printf("data.i = %d\n", data.i);

    // Assign and print float
    data.f = 220.5;
    printf("data.f = %.2f\n", data.f);

    // Assign and print string
    strcpy(data.str, "Hello");
    printf("data.str = %s\n", data.str);

    return 0;
}

Output:

data.i = 10       // May print garbage after data.f is assigned
data.f = 220.50
data.str = Hello

How can we help?

Leave a Reply

Your email address will not be published. Required fields are marked *