Thursday, 17 May 2012

Using Enumerations in C and C++

Whenever you need to define a set of mutually exclusive states, always use an enumeration. Don't use an int and a bunch of #defines. If space is really a premium and you only need a few things, you could settle for a char and a few letters as a code. If you need to represent some states that aren't mutually exclusive, use bitflags (see the next section).
An enumeration is basically an integer type associated with a bunch of special tokens. These tokens can be used for assignment and is-equal or not-equal checks - you can think of them as a sort of special #define.
 
//declare the enumeration _type_
enum BirdState {FLYING, LANDING, STANDING, TAKEOFF, EATING, SLEEPING};

//create a variable of it (in c or c++)
enum BirdState bs1 = SLEEPING;
//create a variable of it (in c++ only)
BirdState bs2 = SLEEPING;

//compare state
if (bs1 == EATING)
   bird1.hungry--;

//set and compare state
if (bs1 == TAKEOFF && bird1.velocity > 0.3)
   bs1 = FLYING;
 
There are some differences between enums in C and C++. First, in C++ you do not need the enum keyword when declaring a variable. Second, in C++ you cannot use general integer operators (such as arithmetic and bitwise operators) on enumerations
 
enum BirdState bs2;  // legal in C and C++
BirdState bs3;       // legal in C++ only

typedef enum BirdState BirdState_t
BirdState_t bs4;     // can use typedef like this
                     // to make it legal in C as well

bs2++;               // Illegal in C++
bs3 = 2;             // Illegal in C++
bs4 = bs2 | bs3;     // Illegal in C++
 

No comments:

Post a Comment