Tutorials Logic, IN info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Website Development
Practice
Quiz Challenge Interview Questions Certification Practice
Tools
Online Compiler JSON Formatter Regex Tester CSS Unit Converter Color Picker
Compiler Tools

C Unions Memory Sharing Use Cases: Tutorial, Examples, FAQs & Interview Tips

What is a Union?

A union is similar to a struct, but all members share the same memory location. The size of a union equals the size of its largest member. Only one member can hold a valid value at a time.

Featurestructunion
MemoryEach member has its own memoryAll members share the same memory
SizeSum of all member sizes (+ padding)Size of the largest member
Active membersAll members can be used simultaneouslyOnly one member is valid at a time
Use caseGroup related dataMemory-efficient storage of one-of-many types

Union Syntax

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

union Data d;
d.i = 10;           // valid
printf("%d", d.i);  // 10

d.f = 3.14f;        // now f is valid; i is overwritten
printf("%f", d.f);  // 3.14
Union vs Struct - Size Comparison
#include <stdio.h>

struct MyStruct {
    int    i;      // 4 bytes
    float  f;      // 4 bytes
    char   str[20]; // 20 bytes
};  // total: ~28 bytes

union MyUnion {
    int    i;      // 4 bytes
    float  f;      // 4 bytes
    char   str[20]; // 20 bytes
};  // total: 20 bytes (size of largest member)

int main() {
    printf("Size of struct: %zu bytes\n", sizeof(struct MyStruct));  // ~28
    printf("Size of union:  %zu bytes\n", sizeof(union MyUnion));    // 20

    union MyUnion u;

    u.i = 42;
    printf("\nu.i = %d\n", u.i);

    u.f = 3.14f;
    printf("u.f = %.2f\n", u.f);
    printf("u.i after setting u.f = %d (corrupted!)\n", u.i);  // garbage

    // Only the last assigned member is valid
    return 0;
}
Union Use Case - Tagged Union (Variant Type)
#include <stdio.h>
#include <string.h>

// Tagged union: struct + union + type tag
typedef enum { TYPE_INT, TYPE_FLOAT, TYPE_STRING } DataType;

typedef struct {
    DataType type;
    union {
        int    i;
        float  f;
        char   str[50];
    } value;
} Variant;

void printVariant(Variant v) {
    switch (v.type) {
        case TYPE_INT:    printf("int:    %d\n",   v.value.i);   break;
        case TYPE_FLOAT:  printf("float:  %.2f\n", v.value.f);   break;
        case TYPE_STRING: printf("string: %s\n",   v.value.str); break;
    }
}

int main() {
    Variant v1 = {TYPE_INT,    .value.i = 42};
    Variant v2 = {TYPE_FLOAT,  .value.f = 3.14f};
    Variant v3;
    v3.type = TYPE_STRING;
    strcpy(v3.value.str, "Hello, Union!");

    printVariant(v1);
    printVariant(v2);
    printVariant(v3);

    return 0;
}

/*
int:    42
float:  3.14
string: Hello, Union!
*/
Key Takeaways
  • A union stores different data types in the same memory location - only one member is valid at a time.
  • The size of a union equals the size of its largest member.
  • Unions are useful for memory-efficient storage when only one field is needed at a time.
  • Unlike structs, writing to one union member and reading from another is undefined behavior in C.
  • Unions are commonly used in embedded systems and network protocol parsing.
  • Tagged unions (union + enum) are a safe pattern to track which member is currently active.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.