C Unions


In C programming, a union is a special data type that allows storing different types of data in the same memory location. Unlike structures, where each member has its own memory, in a union, all members share the same memory. This makes unions memory-efficient when you need to store only one value at a time from a set of multiple data types.

Unions are particularly useful in low-level programming, embedded systems, and situations where memory is limited.

What is a Union?

To define a union, use the union keyword followed by a union tag and member definitions:

union Data {
    int i;
    float f;
    char str[20];
};
  • Data is the union tag.

  • i, f, and str are members sharing the same memory.

Important: Only one member can store a value at any given time. Writing to one member overwrites the existing data in the memory.

Declaring Union Variables

After defining a union, declare variables like this:

union Data d1, d2;
  • Each union variable has enough memory to store the largest member.

  • For example, in the union above, memory is allocated to hold str (the largest member).

You can also combine definition and declaration:

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

Accessing Union Members

Use the dot operator (.) to access union members:

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

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

strcpy(d1.str, "Hello");
printf("d1.str: %s\n", d1.str);
  • After assigning d1.f, the previous value in d1.i is overwritten.

  • Only the last assigned member contains valid data.

Memory Efficiency of Unions

Unions use less memory than structures because all members share the same memory location.

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

struct Example {
    int i;
    float f;
    char str[20];
};
  • Memory for union Data is equal to the largest member (str[20]).

  • Memory for struct Example is the sum of all members, plus padding.

  • This makes unions ideal when only one member is used at a time.

Unions with Pointers

Pointers can be used with unions for dynamic memory access:

union Data d;
union Data *ptr = &d;

ptr->i = 100;
printf("Using pointer: %d\n", ptr->i);
  • The arrow operator (->) is used to access members via a pointer.

  • Useful in functions and dynamic data handling.

Unions and Functions

Unions can be passed to functions by value or by reference:

By value:

void printInt(union Data d) {
    printf("Value: %d\n", d.i);
}

By reference:

void updateFloat(union Data *d, float f) {
    d->f = f;
}
  • Passing by reference is more efficient, especially for larger unions.

  • Functions can read or update union members directly.

Nested Unions

Unions can be nested inside structures for complex data management:

struct Example {
    int type;
    union Data {
        int i;
        float f;
        char str[20];
    } data;
};
  • The type member can indicate which union member is currently valid.

  • This approach is often used in tagged unions for variant data types.

Practical Example: Using Union

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

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

int main() {
    union Data d;

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

    d.f = 220.5;
    printf("d.f = %.2f\n", d.f); // previous i is now overwritten

    strcpy(d.str, "Hello C Union");
    printf("d.str = %s\n", d.str); // previous f is now overwritten

    return 0;
}
  • Demonstrates how assigning one member overwrites the others.

  • Shows memory efficiency by storing multiple types in the same location.

Best Practices

  1. Use unions when only one member is active at a time.

  2. Use a tag member in a struct to track which union member is currently valid.

  3. Avoid reading a member that was not most recently written to—this can cause undefined behavior.

  4. Combine structures and unions for complex applications like network protocols or file formats.

Summary of the Tutorial

Unions in C are a memory-efficient alternative to structures when only one data type needs to be stored at a time. By sharing memory among all members, unions save space and allow flexible handling of different data types. They are widely used in embedded systems, low-level programming, and data parsers. Mastery of unions, especially combined with structures and pointers, is important for writing efficient and professional C programs.


Practice Questions

  1. Define a union Data with members int i, float f, and char str[20]. Assign a value to each member one by one and print them, observing which value remains valid.

  2. Create a union Measurement with int cm, float meters, and float inches. Write a program to store a value in one member and display it.

  3. Define a structure containing a union for storing either int, float, or char[20], along with a type indicator. Assign values and print based on the type.

  4. Write a function that takes a pointer to a union Data and updates the float member.

  5. Write a program using a union to store student marks either as integer or float, depending on input, and print the result.

  6. Create a union Number with int i and double d. Assign both values sequentially and print memory size of the union.

  7. Define a union Value and an array of 3 union elements. Store different types in each element and print them.

  8. Write a program using a union with a pointer, assigning a value through the pointer and printing it.

  9. Implement a program to demonstrate nested union inside a structure, with a tag member indicating the current active union member.

  10. Create a union Variant with members int, float, and char[20]. Assign a string to the char member and print it along with the size of the union.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top