Enumeration?

I am on the topic of user-defined types and I can't understand enumeration. The example in the book is confusing and doesnt make any sense to me. Could someone explain it any better?

The example I got was

enum Animal (CAT, DOG, RODENT);

I understand that Animal is the type and CAT, DOG, and RODENT are the literal constants. I just cant think of anywhere someone would use this.
Last edited on
Everything in the computer is represented by a number.

Often, though, we want to think in terms of real things -- and we don't care what the actual number is.

So, for example, an enumeration for the faces on the cards in a deck can be simply:
1
2
3
4
5
6
7
enum CardFace
  {
  Spades,
  Diamonds,
  Clubs,
  Hearts
  };

The actual value of the number is not important. The programmer can use it with impunity:
1
2
3
4
5
6
7
8
9
struct Card
  {
  CardFace face;
  unsigned suit;
  };

Card my_card;
my_card.face = Spades;
my_card.suit = 1;

Now, if you want to know if a card is the Ace of Spades, just check it:
1
2
3
4
5
if ((my_card.face == Spades)
&&  (my_card.suit == 1))
  {
  cout << "Yes, I am the Ace of Spades!\n";
  }


It has no other purpose but that very abstraction from pure numbers to the kinds of things we think about, in the language we think about it.

Hope this helps.
Topic archived. No new replies allowed.