QP School
Unions and their purposes in C - Printable Version

+- QP School (https://qomplainerzschool.lima-city.de)
+-- Forum: Tutorials (https://qomplainerzschool.lima-city.de/forumdisplay.php?fid=3)
+--- Forum: C 18 Tutorials (https://qomplainerzschool.lima-city.de/forumdisplay.php?fid=32)
+--- Thread: Unions and their purposes in C (/showthread.php?tid=5097)



Unions and their purposes in C - Qomplainerz - 07-25-2023

Unions are similar to structures, but they use the same memory location for all their members. Only one member can be active at a time.

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

int main() {
    union Data data;
    data.i = 10;
    printf("i: %d\n", data.i); // Output: 10

    data.f = 3.14;
    printf("f: %.2f\n", data.f); // Output: 3.14

    strcpy(data.str, "Hello");
    printf("str: %s\n", data.str); // Output: Hello

    printf("Size of union Data: %lu bytes\n", sizeof(data)); // Output: 20 bytes
    return 0;
}