Reputation: 129
I have an enumerated type in C++ and I am trying to write a subprogram that will return the next value in the set. Here is what I have:
enum ChineseZodiacSign { Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Sheep, Monkey, Rooster, Dog, Pig };
ChineseZodiacSign nextSign(ChineseZodiacSign cz)
{ if (cz%12==1)
cz=cz+1
}
I know each value in the enum is indexed starting at 0 but I am unsure how to go about this. Any help would be greatly appreciated.
Upvotes: 0
Views: 54
Reputation: 447
The enum type cannot be converted to an int type. Your line of code here:
ChineseZodiacSign nextSign(ChineseZodiacSign cz)
{ if (cz%12==1)
cz=cz+1
}
is assuming that the enum type is an int and will crash once the program is passed to the compiler.
The Dark is correct in stating that the enum type needs to be converted to an int type then passed back as an enum type.
I'm sorry if I did anything incorrect when posting this - it is my first time.
Upvotes: 0
Reputation: 8514
You can cast it to an integer, perform the arithmetic, then cast it back
ChineseZodiacSign nextSign(ChineseZodiacSign cz)
{
int val = static_cast<int>(cz);
val++;
val = val % 12;
return static_cast<ChineseZodiacSign>(val);
}
you can, of course, write all that in one statement, but I left it separate for readability.
Upvotes: 1