Correct way to get a random number from enum in C?

Correct way to get a random number from enum in C?

 
  enum Resource {ROCK= 1, PAPER = 2,   SCISSORS= 4};


Given this how can I generate a random number in another function

for example shall I write something like this

enum Resource r = [(random() % 3)];

is this the correct way to get random resource?
Last edited on
It's easiest if all enum values are sequential and start from 0.

 
enum Resource {ROCK, PAPER, SCISSORS};

Then you can just do

 
enum Resource r = (rand() % 3);

In this case there is an easy trick to define a constant that contains the number of values in the enum by just putting it last in the list.

 
enum Resource {ROCK, PAPER, SCISSORS, RESOURCE_COUNT};

 
enum Resource r = (rand() % RESOURCE_COUNT);


If the values are non-sequential, like in your example, it's probably best to use a switch or an array to map the random number to an enum value.

1
2
3
4
5
6
7
8
9
10
enum Resource randomResource()
{
	static enum Resource map[] = 
	{
		ROCK,
		PAPER,
		SCISSORS
	};
	return map[rand() % (sizeof(map) / sizeof(map[0]))]
}
Last edited on
Topic archived. No new replies allowed.