Introduction to Unions in C Programming

C Programming @ Freshers.in

In the world of C programming, unions are a fascinating and powerful data structure that every programmer should understand. This article serves as a comprehensive introduction to unions, with real-world examples and insights on how to utilize them effectively.

Understanding Unions

What are Unions?

Unions, like structures, are composite data types in C that allow you to group variables of different data types under a single name. However, unlike structures, unions share memory space among their members. This means that a union can hold only one value at a time, even if it has multiple members.

Declaration and Usage

To declare a union in C, you use the union keyword, followed by the union’s name and its members. Here’s an example:

#include <stdio.h>
// Define a union
union Money {
    int dollars;
    float euros;
    double pounds;
};
int main() {
    // Declare a union variable
    union Money cash;
    // Assign values to union members
    cash.dollars = 100;
    printf("Dollars: %d\n", cash.dollars);
    cash.euros = 75.50;
    printf("Euros: %.2f\n", cash.euros);
    cash.pounds = 150.75;
    printf("Pounds: %.2lf\n", cash.pounds);
    return 0;
}

Output:

Dollars: 100
Euros: 75.50
Pounds: 150.75

In this example, the union Money has three members: dollars, euros, and pounds. Only one member can hold a value at any given time.

Practical Applications

Unions are valuable in various programming scenarios, including:

  • Implementing type conversion.
  • Optimizing memory usage when only one member needs to be active.
  • Working with data structures like variant records.
Author: user