There are several possibilities and conventions to name an enumeration. The first is to use a tag name just after the enum
keyword.
enum color
{
RED,
GREEN,
BLUE
};
This enumeration must then always be used with the keyword and the tag like this:
enum color chosenColor = RED;
If we use typedef
directly when declaring the enum
, we can omit the tag name and then use the type without the enum
keyword:
typedef enum
{
RED,
GREEN,
BLUE
} color;
color chosenColor = RED;
But in this latter case we cannot use it as enum color
, because we didn't use the tag name in the definition. One common convention is to use both, such that the same name can be used with or without enum
keyword. This has the particular advantage of being compatible with C++
enum color /* as in the first example */
{
RED,
GREEN,
BLUE
};
typedef enum color color; /* also a typedef of same identifier */
color chosenColor = RED;
enum color defaultColor = BLUE;
Function:
void printColor()
{
if (chosenColor == RED)
{
printf("RED\n");
}
else if (chosenColor == GREEN)
{
printf("GREEN\n");
}
else if (chosenColor == BLUE)
{
printf("BLUE\n");
}
}
For more on typedef
see Typedef