enum

Hello every body :)

can any one tell me what's the meaning of enum ?

I read it in that code:

enum Suit { clubs, diamonds, hearts, spades };
const int jack = 11; //from 2 to 10 are
const int queen = 12; //integers without names
const int king = 13;
const int ace = 14;

please explain what is enum !

http://www.cplusplus.com/doc/tutorial/other_data_types/

Scroll to the bottom for Enumerations (enum).

It should explain it well enough for you.
an enum is a useful way of replacing a number with a name.

with
enum Suit { clubs, diamonds, hearts, spades };

It is almost the same as
1
2
3
4
const int clubs = 0; 
const int diamonds = 1;
const int hearts = 2;
const int spades = 3;


The advantage is that you don't have to specify a number that it is equal to and yet you are guaranteeing that they are all different.

So now you can say : if (suit == spades) easily in your code.

I wrote a thread lately on enums. Maybe that will help you:
http://cplusplus.com/forum/beginner/73357/
thanks ^_^
Also, if you have
1
2
3
4
5
6
7
8
9
10
11
12
13
14
enum Suit { clubs, diamonds, hearts, spades };

// and a function

void print(Suit suit)
{
  switch (suit)
  {
  case clubs: cout << "Clubs\n"; break;
  case diamonds: cout <<"Diamonds\n"; break;
  case hearts: cout << "Hearts\n"; break;
  case spades: cout << "Spades\n"; break;
  }
}


Then this function must be called with a Suit: print(spade); not print(1);. It protects your function from being called with invalid parameters.

~A typdef:
1
2
3
4
5
typedef int Suit;
#define diamond 0
#define club 1
#define heart 2
#define spade 3 


Would still allow you to make the function: void print(Suit suit);, but since Suit is an int, any int passed through it will get through the compiler. Not as safe.
Last edited on
Topic archived. No new replies allowed.