Lesson 46: Enumerations (enum) and Typedef (typedef)
1. Enumerations (enum)
An enumeration is a user-defined type that assigns names (identifiers) to integer constants. This makes the code more readable and easier to maintain than using raw magic numbers.
Syntax: c enum enum_name { constant1, constant2, ... };
Example
By default, JANUARY is 0, FEBRUARY is 1, and so on.
c enum Month { JANUARY, // 0 FEBRUARY, // 1 MARCH = 3, // Explicitly set to 3 APRIL // Automatically 4 };
int main() { enum Month current_month = JANUARY;
if (current_month == 0) {
printf("It's the start of the year.\n");
}
printf("April value: %d\n", APRIL); // 4
return 0;
}
2. typedef Keyword
typedef provides a mechanism to create aliases (alternate names) for existing data types, simplifying complex declarations like structures and pointers.
Simplifying Structure Declarations
c // Before typedef: struct Person { ... }; struct Person p1;
// After typedef: typedef struct { char name[50]; int age; } Person; // 'Person' is now an alias for the structure
Person p2; // No need for 'struct'
Simplifying Pointers
c typedef int *IntPtr; IntPtr p, q; // p and q are both pointers to integers // Without typedef: int *p, q; (only p is a pointer)