enum animal {
CAT = 1,
DOG = 2,
Elephant = 3,
Monkey = 4
}
...
animal things = ;
for (things = CAT; things <= Monkey; things++)
{
...
}
Mainly what I question is; can I do the "things++" ?
if so, what would happen if I let it overflow ? that is to say, if I did not have the condition of "things <= Monkey"
and just let "things++" run off? would it automatically jump back down to CAT or would it become undefined with a int value of 5+ ?
I guess the things++ operation (increment the value of 'things') doesn't work so you have to spell it out:
Take the value of 'things':
things
Add the value 1:
(things + 1)
Treat that value as if it were an 'animal' instead of an integer. This is called "casting":
(animal)(things + 1)
Store the new 'animal' in the location named 'things':
things = (animal)(things + 1);
(things + 1) would equate to an integer (kinda like an auto cast to an int as a simpler form) , but the resulting integer really isn't an animal unless manually telling it what cast you want?
i.e. ?
things = (animal) 4; // would result into a monkey ?
Seems as though C would be more flexible if you could work on values of an enum directly. But oh well.
If C++ allowed automatic casting of enum types there would be no safety advantage to using the enum over using an int and a bunch of defines (the original C way). When you create an enumeration you are saying you WANT the type checking to protect yourself from programming errors. The explicit cast is telling C++ that you KNOW you are doing an unsafe conversion and you promise not to send the enum out of range. That's probably also why things++ is not allowed: the compiler can't be sure the result will be a valid value.
The following code will replace your enum and eliminate all that pesky type checking:
typedef int animal;
#define CAT 1
#define DOG 2
#define Elephant 3
#define Monkey 4