C Enumerated Types are a powerful feature of the C programming language that allow developers to define custom types that can have a limited set of possible values. By using the typedef
and enum
keywords, we can create these types, making our code more readable and expressive.
To define an enumerated type, we use the following syntax:
typedef enum {
// ...values
} TYPENAME;
It is a convention to name the enumerated type in uppercase letters.
Let’s consider a simple example to illustrate how enumerated types work. Suppose we want to create a BOOLEAN
type that can have values true
or false
. Here’s how we can define it:
typedef enum {
true,
false
} BOOLEAN;
In this case, the example is not very practical because C already provides a built-in bool
type. However, it demonstrates the concept of creating custom types using enumerated types.
Another common use case for enumerated types is to define weekdays. We can create a WEEKDAY
type with values for each day of the week:
typedef enum {
monday,
tuesday,
wednesday,
thursday,
friday,
saturday,
sunday
} WEEKDAY;
Now, let’s see a simple program that uses the WEEKDAY
enumerated type:
#include <stdio.h>
typedef enum {
monday,
tuesday,
wednesday,
thursday,
friday,
saturday,
sunday
} WEEKDAY;
int main(void) {
WEEKDAY day = monday;
if (day == monday) {
printf("It's Monday!");
} else {
printf("It's not Monday");
}
return 0;
}
In the program, we declare a variable day
of type WEEKDAY
and initialize it with the value monday
. We then use an if
statement to check if it’s monday
, and print the corresponding message.
Internally, each item in the enumerated type is assigned an integer value. In our WEEKDAY
example, monday
is assigned the value 0, tuesday
has the value 1, and so on. Although we could use these integer values directly in our code, using names makes our code more readable and easier to understand.
Overall, enumerated types in C are a convenient and effective way to define custom types with a limited set of possible values, making our code more expressive and easier to maintain.