What can I do with an enum variable?
Really what you're doing there is declaring a variable inline with the rest of the definition of the enumeration. It's equivalent to:
enum paint_colors { RED, GREEN, BLUE };
enum paint_colors colors;
Often, you'll see a typedef
associated with the definition:
typedef enum _paint_colors { RED, GREEN, BLUE } paint_colors;
Which lets you use the enumeration more like the built in types:
paint_colors color;
So the answer to your question is that colors
is a variable of type enum paint_colors
, and can be used any way you think is appropriate for such a variable:
colors = RED;
if (colors != GREEN)
{
colors = BLUE;
}
And so on.
Internally, an enum
is treated as an integer that can only hold a limited range of values. In this case, the constants RED
, GREEN
, BLUE
, ... will be defined and will be equal to 0
, 1
, 2
, ... (respectively). The variable colors
can be used anywhere an int
can be used. You can use operators like ++
to iterate through the list of colors. The only difference between declaring enum paint_colors colors
and int colors
is that the enumerated variable can should only be assigned one of the enumerated constants.
This gives you several benefits over using #define
to create a series of constants and using a normal int
for colors
. First, some debuggers can detect that colors
is an enumerated type and will display the name of the enumerated constant instead of a numeric value.
More importantly, this can add an additional layer of type checking. It is not required by the C standard, but some compilers check and make sure that values assigned to a variable of enumerated type correspond to one of the enumerated constants.
Mentally, you can almost think of this is similar to saying:
#define RED 0
#define GREEN 1
#define BLUE 2
typedef int paint_colors;
paint_colors colors;
The variable is treated like an int
, but explicitly giving it a different type helps to clarify what the variable is and what it is used for.