Enum data type in C
Enum data type in C: In C programming, enum (short for enumeration) is a data type that consists of a set of named integer constants. It is a way to define and work with a collection of related constants in a more readable and manageable way.
Here’s a breakdown of how enum works in C:
Basic Syntax of Enum data type in C
enum EnumName {
Constant1,
Constant2,
Constant3,
// ...
};
Example of Enum data type in C
Here’s a simple example of an enum in C:
#include <stdio.h>
enum Day {
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY
};
int main() {
enum Day today;
today = WEDNESDAY;
if (today == WEDNESDAY) {
printf("It's Wednesday!\n");
}
return 0;
}
Understanding enum
- Declaration:
enum Daydeclares a new enumeration type calledDay. - Constants:
SUNDAY,MONDAY, etc., are constants of typeenum Day. - Default Values: By default, the first constant (
SUNDAY) is assigned the value0, the second (MONDAY) gets1, and so on.
Custom Values
You can also assign custom integer values to the constants:
enum Weekday {
SUNDAY = 1,
MONDAY = 2,
TUESDAY = 3,
WEDNESDAY = 4,
THURSDAY = 5,
FRIDAY = 6,
SATURDAY = 7
};
Using enum
Enums can be used in switch statements, comparisons, and more:
enum Color {
RED,
GREEN,
BLUE
};
void printColor(enum Color c) {
switch(c) {
case RED:
printf("Red\n");
break;
case GREEN:
printf("Green\n");
break;
case BLUE:
printf("Blue\n");
break;
default:
printf("Unknown color\n");
}
}
Enumerations and int
Enums are essentially integers:
enum Boolean {
FALSE, // 0
TRUE // 1
};
Size of Enum
The size of an enum type is typically the size of an int, but it can vary based on the compiler and the number of constants.
enum and typedef
You can use typedef to create a new type name for your enum:
typedef enum {
SMALL,
MEDIUM,
LARGE
} Size;
Now you can use Size instead of enum Size:
Size mySize = MEDIUM;
Best Practices of Enum data type in C
- Readability: Use enums to improve the readability of your code by giving meaningful names to constants.
- Scope: Enum constants have global scope but can be restricted using enums in structures or functions.
Summary Table
| Enum Component | Description |
| enum EnumName | Defines a new enumeration type. |
| ConstantName | Represents a named constant in the enumeration. |
| int | Underlying type of enum constants (usually an int). |
| typedef enum | Allows defining a new type name for the enum. |