1-3-1) Simple Types vs Enumerations


In programing many "types" turn out to be some kind of integer range. Nevertheless we might want to distinquish these types from each other.

For example we might consider the suits of a deck of card to be 0..3 and the rank to be 1..13.

It would be nice if one could not accidently assign a suit to a rank or vice versa.

C++ has two simple mechanisms to give integer ranges new names: typedefs and enumerations.

Typedefs are just synonyms; Enumerations however are recognized as a different types and so may be more desirable.

Typedefs are just synonyms

#include <iostream.h>


typedef int Suit; //intent: 0=diamonds, 1=clubs, 2=hearts, 3= spades
typedef int Rank; //intent: 1...13 for ace ... king

void main( )
{

Suit cardSuit = 0;
Rank cardRank = 10;

cardSuit = cardRank; //unfortunately allowed
                     //typedefs are synonyms and not distinct types
cardSuit = 42; //OK
int i = cardSuit; //OK

cout << "card Suit: " << cardSuit << " rank: " << cardRank << "\n";

}

Enumerations are recognized as a different type

#include <iostream.h>


enum Suit {diamond, club, heart, spade};
enum Rank {ace = 1, two=2, three=3, four=4, five=5, six=6,
           seven=7, eight=8, nine=9, ten=10, jack=11, queen=12, king=13};

void main( )
{

Suit cardSuit = heart;
Rank cardRank = three;

//cardSuit = cardRank; //ERROR requires a cast
//cardSuit = 3;  //ERROR requires a cast
int i = cardSuit; //OK

cout << "card Suit: " << cardSuit << " rank: " << cardRank << "\n";

}