Archived

This topic is now archived and is closed to further replies.

Vangelis

Traversing through enums

Recommended Posts

Vangelis    122
Say I have an enumeration like
enum ABILITY
{ 
    ABILITY_walk = 0,
    ABILITY_run,

    ABILITY_count
} 
Now I have function that takes an ABILITY as a parameter.
 void ExecuteAction(ABILITY ability);  
Is there any way I can start at ABILITY_walk, and go through the whole enum until i hit count? Like this...
for(int count = 0; count < ABILITY_count;count++)
{
     ExecuteAction(count);
}  
To go through every value in ABILITY? Or does ABILITY become its own type and only ABILITY's can be passed into the function? [edited by - Vangelis on August 11, 2003 4:29:51 AM]

Share this post


Link to post
Share on other sites
ToohrVyk    1596
A question is burning on my lips : if you wander if this is possible or not, why don''t you try it yourself? It would certainly have been faster than waiting for an answer on a forum.

ABILITY should become its own type, but you can cast it to int and vice versa, so this piece of code might do what you want:


for( int count = 0; count < (int)ABILITY_count; ++count ) {

ExecuteAction( (ABILITY)count );
}


ToohrVyk

Share this post


Link to post
Share on other sites
foofightr    130
An enumeration is just like a series of #defines. The compiler can use the "names" to report more helpful warnings/errors, but for all intents and purposes, an enum value is nothing but an integer. So, your code will work fine.

Share this post


Link to post
Share on other sites
Vangelis    122
I did try it and I got errors like "cannot convert parameter 1 from ''int'' to ''enum ABILITY''", but the casting thing seems to work. Thanks to those who replied, but I''m wondering if enumerations are transparently promoted to int, why I was getting the original error?

Share this post


Link to post
Share on other sites
civguy    308
quote:
Original post by Vangelis
I did try it and I got errors like "cannot convert parameter 1 from ''int'' to ''enum ABILITY''", but the casting thing seems to work. Thanks to those who replied, but I''m wondering if enumerations are transparently promoted to int, why I was getting the original error?
I don''t remember how the automatical promotions went but what I can gather from this thread is this:
enum -> int = ok
int -> enum = not ok


Share this post


Link to post
Share on other sites
foofightr    130
Yeah. Think of it like this.


class ENUM : public INT
{
};

So, an enum is an int, but an int is not an enum (needs to be cast). It was late when I posted my reply and I missed that part of your code... sorry.

Share this post


Link to post
Share on other sites