Your enum
declaration is a bit wrong. It should be
enum words {dog, cat, horse, hen, goat, pig, sheep};
Since C++11 it is usually also better to use an enum class
instead, see this question for details:
enum class words {dog, cat, horse, hen, goat, pig, sheep};
Note that enum
enumerators already have a numeric value. If you don't specify these numeric values manually, they are from left-to-right starting from zero increasing by one. So e.g. horse
has the numeric value 2
in your enumeration.
However, it is not directly allowed to convert between the numeric value and the enumeration implicitly. If you need to do that, you must use static_cast
:
auto word = static_cast<words>(wordno);
When doing this, you need to be careful however (which is also why the explicit cast is required), because you are not allowed to cast an integer value that is outside the range of numeric values of the enumeration in this way. In your code you do rand()%8
which can return values up to 7
, but the largest numeric value in your enumeration is 6
for sheep
. You would have undefined behavior with that.
auto
can be replaced by words
. It just lets the compiler figure out the correct type, so I don't have to write it twice. (It is already in the static_cast
.)
As a sidenote, rand
is not a good random number generator for many reasons (see e.g. this question). Since C++11 you can use the more modern <random> library, see this question.
Also as a sidenote I suggest avoiding C-style casts such as (words)wordno
. Instead use static_cast
as I showed above. You are much less likely to make serious mistakes this way, since the C-style casts are usually too permissive in what casts they allow.
For words word = words[4];
, this syntax does not work. But it is not really necessary, since as above, you can initialize word
directly with the value 4
with an explicit cast.
auto word = static_cast<words>(4);
But if you are intending to assign a constant value, you should just use the enumerator directly. That is what they are for:
auto word = words::goat;