computer science goes bonk / all posts / rss / about

what's in an enum?

Pop quiz, hotshot:

int main() {
  enum Result {
    LOSE = 0,
    WIN,
    DIE_TRYING
  } result;

  switch (result) { 
   case LOSE:
    break;
   case WIN:
    break;
   case DIE_TRYING:
    break;
   default:
    // can't get here?
  }
}

How many possible values can result hold?

...

The answer, of course, is four. In addition to LOSE, WIN, and DIE_TRYING, WIN | DIE_TRYING is a valid value for result.

A rule of thumb is that enums can hold any value that fits into the smallest bit pattern required by the enum. Since the Result enum needs two bits to store 00b, 01b, and 10b, one valid value is 11b, a.k.a. WIN | DIE_TRYING.