8.2) Enumerations and typedef in C
Table of Contents
Enumerations in C
Enumerations, often referred to as enums, are user-defined data types that consist of a set of named integer constants.
Enums make your code more readable and maintainable by providing meaningful names for values.
Example: Using Enumerations
#include <stdio.h>
enum Day {
MONDAY, // 0
TUESDAY, // 1
WEDNESDAY, // 2
THURSDAY, // 3
FRIDAY, // 4
SATURDAY, // 5
SUNDAY // 6
};
int main() {
enum Day today = WEDNESDAY;
if (today == WEDNESDAY) {
printf("It's Wednesday!\n");
} else {
printf("It's not Wednesday.\n");
}
return 0;
}
Output:
It's Wednesday!
In this example, the enum Day
defines a set of constants starting from MONDAY
with a default value of 0. The variable today
is assigned the value WEDNESDAY
, which is 2. The program then checks if today
is equal to WEDNESDAY
and prints the corresponding message.
typedef in C
The typedef
keyword allows you to create aliases for existing data types, making your code more readable and abstracting away implementation details.
Example: Using typedef
#include <stdio.h>
typedef int Age;
int main() {
Age personAge = 25;
printf("Age: %d\n", personAge);
return 0;
}
Output:
Age: 25
In this example, typedef
is used to create an alias Age
for the int
data type. This improves code readability and can make your code more maintainable.
Using Enumerations with typedef
Enums can be combined with typedef
to create a more intuitive and concise way to define data types.
Example: Using Enumerations with typedef
#include <stdio.h>
typedef enum {
SMALL,
MEDIUM,
LARGE
} Size;
int main() {
Size shirtSize = MEDIUM;
switch (shirtSize) {
case SMALL:
printf("Small size.\n");
break;
case MEDIUM:
printf("Medium size.\n");
break;
case LARGE:
printf("Large size.\n");
break;
}
return 0;
}
Output:
Medium size.
In this example, an enumeration for Size
is defined using typedef
, and the Size
type is used to declare the shirtSize
variable. The program then uses a switch
statement to print the appropriate size message.
Enumerations and typedef
are powerful tools that help improve code readability, maintainability, and abstraction. They make your code more understandable by providing meaningful names for values and creating more intuitive data types.