How can I define an enumerated type (enum) in C?
c, enums
Solution
Declaring an enum variable is done like this:
enum strategy {RANDOM, IMMEDIATE, SEARCH};
enum strategy my_strategy = IMMEDIATE;
However, you can use a `typedef` to shorten the variable declarations, like so:
typedef enum {RANDOM, IMMEDIATE, SEARCH} strategy;
strategy my_strategy = IMMEDIATE;
Having a naming convention to distinguish between types and variables is a good idea:
typedef enum {RANDOM, IMMEDIATE, SEARCH} strategy_type;
strategy_type my_strategy = IMMEDIATE;
Problem
I'm not sure what the proper syntax for using C enums is. I have the following code: ``` enum {RANDOM, IMMEDIATE, SEARCH} strategy; strategy = IMMEDIATE; ``` But this does not compile, with the following error: ``` error: conflicting types for ‘strategy’ error: previous declaration of ‘strategy’ was here ``` What am I doing wrong?