07-25-2023, 01:22 PM
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;
}
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
https://www.youtube.com/channel/UCxfkGVU...2mQ/videos