1. Unions (union)
A union is a user-defined data type similar to a structure, but with a critical difference in memory usage. While a struct allocates memory for all its members, a union allocates memory for only the largest member. All members of a union share the same memory location.
- Purpose: Unions are used for memory optimization when you know that only one of the members will be actively used at any given time.
A. Defining a Union
The syntax for defining a union is identical to defining a structure, but uses the union keyword.
union Data {
int i;
float f;
char str[20];
};
B. Memory Allocation
If an int is 4 bytes, a float is 4 bytes, and char str[20] is 20 bytes, the total memory allocated for a variable of type union Data will be 20 bytes (the size of the largest member, str).
C. Accessing Members
Members are accessed using the dot operator (.) or the arrow operator (->) just like structures. However, you must only access the member that was most recently written to. Writing to one member overwrites the data in the others.
union Data data;
data.i = 10;
printf("Data.i: %d\n", data.i);
data.f = 220.5;
// WARNING: The previous value of data.i is now corrupted/overwritten
printf("Data.f: %.1f\n", data.f);
// Accessing the corrupted integer member
printf("Data.i (corrupted): %d\n", data.i);
2. Enumerations (enum)
An enumeration (enum) is a user-defined data type that consists of a set of named integer constants.
- Purpose: To make code more readable and maintainable by allowing the programmer to use descriptive names instead of “magic numbers.”
A. Defining an Enum
The enum keyword creates a new type containing a list of identifiers (the names).
enum Weekday {
MON, // 0 by default
TUE, // 1
WED, // 2
THU, // 3
FRI, // 4
SAT, // 5
SUN // 6
};
B. Default and Explicit Values
By default, the first identifier is assigned the integer value 0, and each subsequent identifier is incremented by 1. You can override these defaults:
enum Status {
ERROR = -1,
PENDING = 0,
SUCCESS = 10,
CRITICAL // This is automatically 11
};
C. Using Enum Constants
Once defined, you can declare variables of the enum type and use the named constants in your code. The compiler treats these constants as integers.
enum Status current_status = SUCCESS;
if (current_status == SUCCESS) {
printf("Operation completed with status code: %d\n", current_status);
// Output: 10
}
