QP School

Full Version: Unions and their purposes in C
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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;
}