2

Possible Duplicate:
generating random enums

Lets say I have the following:

enum Color {        
    RED, GREEN, BLUE 
};
Color foo;

What I want to be able to do is randomly assign foo to a color. The naiive way would be:

int r = rand() % 3;
if (r == 0)
{
    foo = RED;
}
else if (r == 1)
{
    foo = GREEN;
}
else
{ 
    foo = BLUE;
}

I was wondering if there was a cleaner way of doing this. I have tried (and failed) the following:

foo = rand() % 3; //Compiler doesn't like this because foo should be a Color not an int
foo = Color[rand() % 3] //I thought this was worth a shot. Clearly didn't work.

Let me know if you guys know of any better way which does not involve 3 if statements. Thanks.

Community
  • 1
  • 1
user1413793
  • 9,057
  • 7
  • 30
  • 42

2 Answers2

7

You can just cast an int to an enum, e.g.

Color foo = static_cast<Color>(rand() % 3);

As a matter of style, you might want to make the code a little more robust/readable, e.g.

enum Color {        
    RED,
    GREEN,
    BLUE,
    NUM_COLORS
};

Color foo = static_cast<Color>(rand() % NUM_COLORS);

That way the code still works if you add or remove colours to/from Color at some point in the future, and someone reading your code doesn't have to scratch their head and wonder where the literal constant 3 came from.

Paul R
  • 208,748
  • 37
  • 389
  • 560
  • 2
    Thanks so much. And thank you for the style tip I actually never thought of that but its quite clever! – user1413793 Jun 06 '12 at 08:42
  • @PaulR, OP: Note that this works based on the (valid) assumption that the enum range is contiguous - which is not always the case. – einpoklum Aug 15 '16 at 13:44
1

All you need is a cast:

foo = (Color) (rand() % 3);
slaphappy
  • 6,894
  • 3
  • 34
  • 59