enum in c

 

Photo by Bernard Hermant on Unsplash

You must have seen the word enum if you have done any programming.As we all know there is 32 keyword in c, enum is also one of them..

Screenshot from Programming in ANSI C book by E Balaguruswamy | screenshot by author

But what is this actually?
Just as there is a user-defined function in every programming, in the same way, there is a user-defined function as well as a user-defined data type.

This means that an enum is a user-defined data type in C that consists of a set of named integer constants. Also known as Enumerations.

General form:

enum identifier_name {value1, value2,…….valuen};

Here.. identifier_name is a user-defined enumerated data type that can be used to declare a variable.

enum DaysOfWeek {
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY
};

Here names of weeks like SUNDAY, MONDAY… are known as enumeration constant. By default, the first constant (SUNDAY) is assigned the value 0, and subsequent constants are assigned values in increasing order.

Using Enumerations

Once you’ve declared an enumeration, you can use it just like any other data type in your C code. Here are a few common use cases for enums:

Improved Code Readability

Enums can make your code more readable by replacing cryptic integer values with descriptive names. Consider the following function signature:

void setDay(int day);

Without context, it’s unclear what values are valid for day. By using an enumeration, you can make the function more self-explanatory:

void setDay(enum DaysOfWeek day);

Now, it’s clear that day should be one of the days of the week.

Switch Statements

Enums are often used with switch statements to create more understandable and maintainable code. For example:

enum Color {
RED,
GREEN,
BLUE
};
void printColor(enum Color color) {
switch (color) {
case RED:
printf("The color is red.\n");
break;
case GREEN:
printf("The color is green.\n");
break;
case BLUE:
printf("The color is blue.\n");
break;
default:
printf("Unknown color.\n");
}
}

Enum as Flags

You can also use enums to create bit masks for representing combinations of options or states. This is particularly useful in systems programming and working with hardware registers. Here’s a simple example:

enum Permissions {
READ = 1,
WRITE = 2,
EXECUTE = 4
};
int main() {
// Combine permissions using bitwise OR
enum Permissions myPermissions = READ | WRITE;

// Check for specific permissions using bitwise AND
if (myPermissions & WRITE) {
printf("Write permission granted.\n");
}

return 0;

Tags
What is a enum in C?
What is enum with example?
What is enum in type?
typedef enum in c
enum in c example
enum in c++
size of enum in c
enum in c syntax
is enum a built in library in c
use of enum in c
typedef enum in c example

Post a Comment

Previous Post Next Post