Unions & Enumerations (enum)
union Data {
int i;
float f;
char c;
};
int main() {
union Data d;
d.i = 10;
printf("%d\n", d.i); // 10
d.f = 3.14; // overwrites the SAME memory that stored d.i
printf("%f\n", d.f); // 3.14, but d.i is now garbage!
return 0;
}
Unlike a structure, where every member gets its own separate memory, all members of a union share the exact same memory location. The union's total size equals only its largest member, not the sum of all members — this is the whole point of using one.
Unions are used when you know only one of several possible fields will be needed at any given moment, and you want to save memory rather than reserving space for all of them simultaneously — common in embedded systems and low-level protocol parsing, where every byte of memory matters.
enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY };
int main() {
enum Day today = WEDNESDAY;
if (today == WEDNESDAY) {
printf("Midweek!\n");
}
printf("%d\n", today); // 2 - enums are just labeled integers
return 0;
}
By default, an enum's values start at 0 and count upward, so MONDAY is 0, TUESDAY is 1, and so on.
Compare if (status == 2) to if (status == SHIPPED) — the second version documents itself, letting anyone reading your code immediately understand what the value represents without needing to remember what each raw number means. This is the whole purpose of enums: replacing unclear "magic numbers" with meaningful names.
Because every field in a union shares the same memory, writing to one field and then reading a different field afterward gives you garbage, misinterpreted data — this is expected union behavior, not a bug, but it catches beginners off guard until they understand that a union only ever holds one valid value at a time.
Define an enum representing order status (PENDING, SHIPPED, DELIVERED, CANCELLED) and write a program that prints a message depending on the current status.
#include <stdio.h>
enum Status { PENDING, SHIPPED, DELIVERED, CANCELLED };
int main() {
enum Status orderStatus = SHIPPED;
if (orderStatus == SHIPPED) {
printf("Your order is on the way!\n");
} else if (orderStatus == DELIVERED) {
printf("Your order has arrived.\n");
} else {
printf("Order status: %d\n", orderStatus);
}
return 0;
}