ints and enums

If I have some enum like

 
enum direction{up,down,left,right};


And I want to generate a random direction.
I can generate a random number from 0-4 but, as I understand, an enum can be assigned to an int but an int cannot be assigned to an enum?

Is there some better way to do this other than a switch statement to check case 0 direction=up...and so on?
I can generate a random number from 0-4
You need a number in the range 0-3.

but, as I understand, an enum can be assigned to an int
You can override the type system; that's what a cast is.
1
2
3
4
5
6
7
8
9
10
#include <cstdlib>

enum direction { up, down, left, right };

int main()
{
        srand(0);
        int n = rand() % 3;
        direction d = static_cast<direction>(n);
}
Thanks
Topic archived. No new replies allowed.