Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Unions and their purposes in C
#1
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;
}
Also follow me on Youtube for videos about video games:
https://www.youtube.com/channel/UCxfkGVU...2mQ/videos
Reply


Messages In This Thread
Unions and their purposes in C - by Qomplainerz - 07-25-2023, 01:22 PM

Forum Jump:


Users browsing this thread: 3 Guest(s)