enums

could someone explain how this would display 1
1
2
3
enum Season {Spring, Summer, Fall, Winter} favoriteSeason; 
 favoriteSeason = Summer;
 cout << favoriteSeason;
enums are a collection of named integer constants. By default they are numbered 0,1,2,... but you can over-ride that. summer is 1, then, since spring is 0 ... and fall is 2 and winter is 3...

a bit more than the reference will tell you:

you cannot print the text of an enum easily (just like you can't print a variable name easily). you either need a macro or a lookup table:
string seasonwords[] = {"Spring", "Summer", "Fall", "Winter"};
cout << seasonwords[favoriteseason];

or you can use a map or similar table of pairs that associate 0 and "Spring" together, etc.

enums are really good for making your code pretty, so instead of table[0] and table[1] all over the code, you have table[spring] or table[fall] and can better see what it means. Its just a readability aid, at that level. You can do more with them, like putting in bogus entries to control iteration:
enum s{spring, summer, hot, fall, winter, cold};
for(x = hot; x < cold; x++)
... iterates fall and winter

or use them to control compile time array sizes:
enum Season {Spring, Summer, Fall, Winter, Seasonmax};
string allseasons[Seasonmax]; //if you insert a new season 'monsoon' or something after fall, the array gains a location next time you compile, automatically!
Last edited on
Enumerated constant types (enum):
https://www.learncpp.com/cpp-tutorial/enumerated-types/

They are a constant alias for integers.

C++ also has enumerated classes that aren't a direct alias to integers without casting:
https://www.learncpp.com/cpp-tutorial/enum-classes/
thank you all
Topic archived. No new replies allowed.