I've been playing around with enumerators the past couple of days. Would some one mind telling me what the real world application of enum is? So far I fail to see any value in using the data type and it definitely doesn't seem to be flexible. I'm wondering how it might be used in business app development and game development.
enums are very handy when you have a limited range of valid values which are associated with non-integral concepts:
1 2 3 4 5
class node
{
node* links[3];
enum dir{left=0,right=1,parent=2};
};
If you do such a thing with integral values, you *will* get it wrong someplace. And if not you, the poor programmer maintaining the application. (And not using an array for the links would mean that you require a lot of algorithms to be coded twice, e.g. AVL tree rotation, which can be done in one function this way: void rotate(dir d) {link[dir]=...} and called intuitively: rotate(left)).
It's only real application is to enforce a bit of type safety, though that the C++ standard does not consider enums to be full-blown types is annoying.
Suppose I have this code:
1 2 3 4 5 6 7 8 9 10 11
#define APPLE 1
#define ORANGE 2
#define GRAPE 3
#define CORN 1
#define PEA 2
#define SQUASH 3
void consume( int fruit, int vegetable ) {
// ...
}
It is very easy to call consume() with the arguments reversed, and you'll get no compile errors:
consume( PEA, ORANGE ); // Params in the wrong order! PEA is not a fruit!
enums solve this problem:
1 2 3 4 5 6 7 8 9 10 11 12 13
enum Fruit {
APPLE, ORANGE, GRAPE
};
enum Vegetable {
CORN, PEA, SQUASH
};
void consume( Fruit f, Vegetable v ) {
// ...
}
consume( CORN, PEA ); // Compile error, CORN not a fruit