Apply for Zend Framework Certification Training

c




< Structure in C Last >



What is a Union in C?
 
A union is a user-defined data type (like a structure) that allows you to store different types of data in the same memory location.
Key Idea:
At any time, a union can hold only one value (one member).
Syntax of Union
union union_name {
    data_type member1;
    data_type member2;
    ...
};
Example:
union Data {
    int i;
    float f;
    char c;
};
 
Declaring and Using a Union
#include <stdio.h>
union Data {
    int i;
    float f;
    char c;
};
int main() {
    union Data d;
    d.i = 10;
    printf("Integer: %d\n", d.i);
    d.f = 3.14;
    printf("Float: %f\n", d.f);
    d.c = 'A';
    printf("Char: %c\n", d.c);
    return 0;
}
 
Important:
When you assign a new value, the previous value is overwritten.
Memory Concept of Union
In a union:
All members share the same memory location
Size of union = size of largest member
Example:
union Test {
    int i;      // 4 bytes
    float f;    // 4 bytes
    char c;     // 1 byte
};
Size of union = 4 bytes (largest member)
 
Memory Difference: Structure vs Union
Feature Structure Union
Memory Allocation Separate memory for each member Shared memory
Size Sum of all members Size of largest member
Access All members can be used simultaneously Only one member at a time
Data Safety Values remain intact Values get overwritten
Example: Structure vs Union
Structure Example:
struct Student {
    int id;
    float marks;
};
Memory = 4 + 4 = 8 bytes
Union Example:
union Student {
    int id;
    float marks;
};
Memory = 4 bytes only
 
Real-Life Example
Think of a memory card slot:
Structure = Multiple slots → store many things at once
Union = One slot → can hold only one item at a time
Example:
union Payment {
    int cash;
    float online;
};
Either cash OR online payment stored — not both at same time.
When to Use Union?
Use unions when:
Memory is limited
Only one value is needed at a time
Working with hardware or embedded systems
 
Key Points to Remember
? Union shares memory
? Only one member is valid at a time
? Size = largest member
? Writing one member destroys others
? Useful for memory optimization
 
Quick Summary
Structure → More memory, more flexibility
Union → Less memory, one value at a time

< Structure in C Last >



Ask a question



  • Question:
    {{questionlistdata.blog_question_description}}
    • Answer:
      {{answer.blog_answer_description  }}
    Replay to Question


Back to Top