C++ enumeration type

Posted by Nick Cash on Thu 21 Dec 2006 02:00 AM — 4 posts, 20,437 views.

USA #0
Hello again everyone!

While working on a small project I decided to use C++'s enumeration type, which looks like this:

enum EState { eSamsara, eMind, eBody, eSoul, eDamian, eNirvana };


I've consulted a few documents briefly on using it within loops, and as far as I can see its only a pain in the neck. There are no attributes like Ada, and you can't just add one like you could in C. I want to do a loop like this:

for ( EState state = eSamsara; state < eNirvana; state++ )
{
  // code here
}

However, the only way I've been able to get it to work is to have a switch to handle each case to update state for the next iteration or to break if need be, which is a huge pain in the neck. Should I scrap the enum data type for another or am I missing something?

Thanks. :)
Amended on Thu 21 Dec 2006 02:02 AM by Nick Cash
USA #1
You should be able to do that loop. I've done it before, are you getting an error message?

Oh yeah, now I remember. You need to make it an int, then cast it. I think.
USA #2
Not a very good looking solution, but it does work as noted below:

for ( int state = (int)eSamsara; state < (int)eNirvana; state++ )
{
  // code here
}

Casting all of the constants is quite a pain, but at least it works. Were this not a short term project I'd look for a more elegant solution.

[EDIT]
Interestingly enough, within the loop I can cast state to EState with no dreary side effects, saving me quite a few casts. I still dislike such dirty casting. Always good to learn something new though.

Thanks Zeno.
Amended on Thu 21 Dec 2006 03:32 AM by Nick Cash
USA #3
This actually makes sense if you think of enumerations as not being sequences but as a special data type that can take one of several values. Being able to increment over them is a left-over from C's implementation of enumerations as integers. But really, an enumeration shouldn't be thought of as a series of numbers; that's why it forces you to cast them. (It is a bit clumsy, of course, when you want to iterate over all values of an enum, without caring what order you get them in. Java lets you do that quite nicely.)



EDIT:
P.S. I just got back from a vacation, hence my absence the past two weeks. :)