Enumerations in C, the good, the bad and the ugly

I’ve started to brush up on my C programming and learn the language properly. So, after reading through a chapter in the famous White Bible, i’ve come to the conclusion that C enumerations are pretty bad.

C enumerations have a nice syntax and they are really handy when defining a range of constants with unique int values, but, and here’s the big issue, they are not type checked against a particular named enum, they are only checked that they are an int! Take this code:

Here, we define an enum called ‘state’ with a few values and require the ‘GetState()’ function to return one of these as it’s type. Unfortunately i can bypass the defined type merely by changing the return statement in the  GetState  call to:

With this change the function still returns totally fine with an int type instead of an enum value as specified! The compiler doesn’t even give you a warning!

Here’s another example with a function expecting an enum as a parameter:

If we change the  GetState  call to:

The compiler still doesn’t complain!

To me, this seems very dangerous and very prone to error, but when talking to C gurus, they’re happy about this, as they like the flexibility C affords with such things, but it begs the question why bother to use an enum type? I’m guessing it’s so the source code becomes self documenting and it becomes clear what a function should expect as a parameter or as a return value, etc. but, remember, don’t rely on any help from the compiler, your on your own with enums.

Enumerations in C, nice to define and use but NOT checked at compile time, remember that.

Incidentally, C++ puts this ‘right’ and type checks all enumerations.

No comments yet.

Submit a Comment

We would love to hear your thoughts. Feel free to submit a comment and join the conversation!

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">