Skip to main content

Structures & Enum - advanced

Internally, an enum uses integers and links these names to values. It is possible to impose a value to a specific field, if you want to use them numerically.

enum color
{
GREEN, /* If not specified, the first value is 0 */
RED, /* Other values are the precedent value + 1. Here, RED == 1 */
BLUE = 20, /* We impose BLUE == 20 */
YELLOW /* Not specified, YELLOW == BLUE + 1 == 21 */
};

Here is a useful example that associates some data to each field:

void print_direction(enum direction dir)
{
/* Mapping from direction to string */
const char *map[] =
{
"north", "south", "east", "west"
};

printf("I am facing %s!", map[dir]);
}

An enumeration may be a field of a structure:

struct character
{
int life;
char name[25];
enum direction dir;
};

/* Direct initialization syntax, just like arrays */
struct character mario =
{
100, "Mario", NORTH
};
printf("It's a me, %s!", mario.name);