Introduction to C Enumerated Types
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:
1 | typedef enum { |
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:
1 | typedef enum { |
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:
1 | typedef enum { |
Now, let’s see a simple program that uses the WEEKDAY
enumerated type:
1 |
|
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.
tags: [“C programming”, “Enumerated types”, “Typedef”]