C enum (Enumeration)

In C, an enum (short for "enumeration") is a user-defined data type that represents a set of named integer constants. Enums are used to make code more readable and self-explanatory by giving meaningful names to values that have a logical relationship.

Syntax
enum enum_name { value1, value2, ..., valueN };

The values within the enum are represented as integer constants, where value1 is 0, value2 is 1, and so on.

Defining an Enum

Here's an example of defining an enum to represent the days of the week:

enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };

Assigning Values to Enum Constants

By default, the first value in an enum is assigned 0, and each subsequent value is incremented by 1. However, you can explicitly assign values to enum constants:

enum Months { January = 1, February, March, April, May, June, July, August, September, October, November, December };

In this example, January is assigned a value of 1, and subsequent months are automatically incremented by 1.

Using Enum Constants

You can use enum constants in your code to make it more readable and self-explanatory.

enum Days currentDay = Wednesday;

Here, currentDay is set to the enum constant Wednesday.

Switch Statements with Enums

Enums are often used in switch statements to improve code readability.

switch (currentDay) { case Sunday: printf("It's a lazy Sunday!\n"); break; case Wednesday: printf("It's hump day!\n"); break; default: printf("It's a regular day.\n"); }

Size of Enums

The size of an enum constant is typically an int. If you need a smaller or larger data type, you can explicitly specify it.

enum SmallEnum : unsigned char { A, B, C };

In this case, the enum SmallEnum uses an unsigned char data type for its constants.

Enum Constants as Flags

Enums are often used to create flag values that can be combined with bitwise operations.

enum Permissions { Read = 1, Write = 2, Execute = 4 }; int userPermissions = Read Write; // Represents read and write permissions

This allows you to use enums to represent and manipulate sets of flags.

Conclusion

enum in C is a convenient way to create named integer constants, improving code readability and maintainability. Enums can be used for representing sets of related values, and they are often used in switch statements, as flag values, or in situations where it's important to give meaningful names to numeric constants.