C enumerations
Created By: chatGPT
Enumerations in C are a user-defined type that consists of a set of named integral constants. This helps increase code readability and maintainability by replacing numerical constants with meaningful names.
enum Color {
RED,
GREEN,
BLUE
};
You can also assign specific values to the enumerators. If you don't assign a value, the first enumerator starts at 0 and each subsequent enumerator gets the next integer value.
enum Position {
LEFT = 1,
CENTER = 5,
RIGHT
}; // RIGHT will have the value 6
To use an enum, declare a variable of the enum type. You can then assign it one of the defined enumerators.
enum Color myColor;
myColor = RED;
Important: Enums are not strictly type-checked like other types, so you can assign an integer directly to an enum variable, but it's generally discouraged.
myColor = 4; // This is permitted but not recommended
You can also add functionality to your enumerations by utilizing them in switch statements, allowing you to handle various cases in a clear and organized manner.
switch (myColor) {
case RED:
printf("Color is red\n");
break;
case GREEN:
printf("Color is green\n");
break;
case BLUE:
printf("Color is blue\n");
break;
default:
printf("Unknown color\n");
}