C Enum
Syntax
enum [tag] { constant1 = value1, constant2 = value2, ..., constantN = valueN } var;
Example
#include <stdio.h>
enum Weekday { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };
int main() {
enum Weekday day = Wednesday;
printf("Today is %d\n", day);
return 0;
}
Output
Today is 2
Explanation
An enum
is a user-defined data type in C that consists of a set of named constants. Each of the named constants is assigned an integer value, which defaults to starting at zero and incrementing by one for each subsequent constant. enum
is useful for making code more readable and less error-prone, especially when dealing with a set of related constants.
Use
The enum
keyword can be used in C to define a new data type consisting of a set of named constants, each with an underlying integer value. These named constants can then be used throughout a program in place of their constant values. This makes code more readable and less error-prone, especially when dealing with related constants.
Important Points
- An
enum
is a user-defined data type consisting of a set of named constants, also known as enumerators. - Each constant is associated with an integer value, which defaults to starting at zero and incrementing by one for each subsequent constant.
- Constants can be explicitly assigned an integer value by specifying the value after the name of the constant.
- Like other data types, an
enum
can be used to declare variables, structures, and function arguments of that type. - An
enum
is not guaranteed to have a size or underlying data type, but it is usually equivalent to an unsigned integer.
Summary
An enum
is a user-defined data type in C that consists of a set of named constants. Each constant is associated with an integer value, which defaults to starting at zero and incrementing by one for each subsequent constant. enum
is useful for making code more readable and less error-prone when dealing with a set of related constants. Understanding the syntax and use of enum
is important for writing clear and efficient C code.