C enums
Explanation of C Enums
Enums in C are a way to define a set of named constants. Each constant in the enum is assigned an integer value, starting from 0 by default, and incremented by 1 for each subsequent constant. Enums provide a way to create more readable and maintainable code by giving meaningful names to values.
Here are the steps to define and use enums in C:
Enum Declaration: To declare an enum, use the
enum
keyword followed by the name of the enum. For example:c enum Color { RED, GREEN, BLUE };
In this example, we declare an enum namedColor
with three constants:RED
,GREEN
, andBLUE
. By default,RED
will have a value of 0,GREEN
will have a value of 1, andBLUE
will have a value of 2.Enum Variable Declaration: To declare a variable of the enum type, use the enum name followed by the variable name. For example:
c enum Color favoriteColor;
In this example, we declare a variable namedfavoriteColor
of typeenum Color
.Enum Value Assignment: To assign a value to an enum variable, use the enum constant name. For example:
c favoriteColor = RED;
In this example, we assign the valueRED
to thefavoriteColor
variable.Enum Comparison: Enums can be compared using the usual comparison operators (
==
,!=
,<
,>
,<=
,>=
). For example:c if (favoriteColor == RED) { printf("The favorite color is red.\n"); }
Switch Statement: Enums are often used in switch statements to perform different actions based on the enum value. For example:
c switch (favoriteColor) { case RED: printf("The favorite color is red.\n"); break; case GREEN: printf("The favorite color is green.\n"); break; case BLUE: printf("The favorite color is blue.\n"); break; default: printf("Invalid color.\n"); break; }
In this example, different actions are performed based on the value of thefavoriteColor
variable.
That's a brief explanation of how to use enums in C. Enums provide a way to define a set of named constants, making the code more readable and maintainable.