enums in C



Enums are notoriously weakly typed in C. While pondering this the other day it occurred to me that instead of writing an enum like this:
enum suit { clubs, hearts, diamonds, spades };
you could write it like this:
struct suit
{
    enum { clubs, hearts, diamonds, spades } value;
};
The struct wrapper adds a modicum of type safety. It also allows you to forward declare suit (you can't forward declare enums). The enumerators (clubs, hearts, diamonds, clubs) are still visible and can be used when a compile time value is required (e.g., switch cases). As usual, caveat emptor.

3 comments:

  1. I think you meant for the second "clubs" (or the first one even) to be "spades".

    ReplyDelete
  2. Ooops. Well spotted. Thanks

    ReplyDelete
  3. Just linked in here from your latest (at time of writing post), http://jonjagger.blogspot.com/2011/04/forward-declaring-stdstring-in-c.html

    This technique (wrapping an enum in a struct) is something I use quite often (in C++). As well as giving the enum a stronger type you can also make it read more descriptively. e.g I'd write your example as:

    struct SuitIs
    {
    enum OfType{ Clubs, Hearts, Diamonds, Spades };
    };

    Now you can write code like:

    SuitIs::OfType suitType = SuitIs::Clubs;

    ReplyDelete