Enum in C with Example
In C, an enumerated type (or “enum”) is a user-defined data type that consists of a set of named values. The names are usually identifiers that behave as constants in the program.
Here’s an example of how we might use an enum in C:
enum color { RED, GREEN, BLUE };
enum color background = GREEN;
In this example, we’ve defined an enum called “color” with three possible values: RED, GREEN, and BLUE. We’ve also defined a variable called “background” and set it equal to GREEN.
We can also specify the underlying type for an enumeration.
enum fruit : char { APPLE='a', ORANGE='o', BANANA='b'};
An enumerated type in C can be treated like any other basic data type (such as int or char) in terms of operations such as assignment and comparison. In the example above, we can do things like compare background
with other colors or assign it a new value, like so:
if (background == RED)
printf("The background is red.\n");
else if (background == GREEN)
printf("The background is green.\n");
else
printf("The background is blue.\n");
background = BLUE;
Another possible use of an enum would be in a switch statement.
switch(background){
case RED:
printf("The background is red\n");
break;
case GREEN:
printf("The background is green\n");
break;
case BLUE:
printf("The background is blue\n");
break;
default:
printf("Invalid Color\n");
}
Note that in C the underlying type of an enumeration is int. Enumeration constants are of type int. The first enumerator has value 0, the next 1, and so on, unless explicit values are specified.
Leave a Comment