I'm new to C++. I've read my first programming book. I've decided to revisit enumeration chapter. And honestly, I don't see why enumeration is useful at all.
Everything you can do with enumeration can also be done with int, double, bool, string, etc without any added difficulty.
I've created the code below to understand how enumeration works, and I gotta say, I am not impressed.
The only advantage I see is possible readability of the code, but other than that, I think enumeration is pretty useless. Of course, I could be wrong.
Do you know of any brilliant ways to utilize enumeration?
#include <iostream>
enum colors { BROWN, BLUE, RED, GREEN, YELLOW };
enum coins { PENNY, NICKETL, DIME, HALFDOLLAR, DOLLAR };
colors returnColorForCoin ( coins coin );
int main() {
colors color;
color = BROWN;
std::cout << color << std::endl; // Notice that it only prints the value stored for BROWN, not the string
if ( color == BROWN ) // You can indirectly prints the actual string of ENUM this way
std::cout << "BROWN" << std::endl;
// color ++; // This is illegal. ENUM variables can't be incremented this way.
color = static_cast < colors > ( color + 1 ); // This is how you increment ENUM variable
std::cout << color << std::endl;
// Indirectly print the value of ENUM color. The value of ENUM can't be printed directly
if ( color == BLUE )
std::cout << "BLUE" << std::endl;
// This is true. ENUM values can be used in relational operations
if ( BROWN < BLUE )
std::cout << "BROWN < BLUE is true" << std::endl;
// This is how you utilize ENUM in a loop. Supposedly, this increases the readability
for ( color = BROWN ; color <= YELLOW ; color = static_cast < colors > ( color + 1) )
std::cout << color << ' ';
// ENUM can be used as a parameter to a function and a function can return ENUM type variable
std::cout << std::endl << returnColorForCoin ( PENNY ) << std::endl;
// This is Anonymous Data Types. Variable can be declared without the name of Data Type
enum { BASKETBALL, FOOTBALL, BASEBALL, HOCKEY } mySport;
mySport = FOOTBALL;
std::cout << mySport << std::endl;
return 0;
}
colors returnColorForCoin ( coins coin ) {
colors color;
color = static_cast < colors > ( coin );
return color;
}
This is just psuedo code so you can't compile this.
1 2 3 4 5 6 7
While GameState == PLAY.
If (user closes the window)
GameState == EXIT
elseif (user opens main menu)
GameState == MAINMENU
and so on. Enums are basically inetegers, but in the form of Text/Names. Bool can hold only true or false, that's 2 states, I want more, a game usually has many more states than the ones I presented.
If you ever write a program that takes command line arguments, you will be very glad for enums. For one or two arguments it is not bad, but with more than that, and optional arguments, it is difficult to keep track of which one is which. I recently had to do this in Java where it is not possible to make a simple enum. I worked around it with a long list of constants, but that is pretty sloppy.