Reputation: 868
I'm wondering about the differences of using typedef + constants in C++ versus using an enum list. The reason the difference seems to matter to me is because the enum I'd use would have a break in continuity in the middle forcing 'ugly'
Example of a deck of cards with both methods where you need to define new types for the values and suits of a card:
enum Value{
ace = 1,
//Biggest issue is I dont want to have two = 2 etc. until 10
jester = 11,
queen = 12,
king = 13
};
In this example the problem is if I want a new Value to be numerical, lets say 7 I can't do:
Value a_value = 7; //Won't allow int to Value
Value a_value = seven; //This extra enum seems just bad
Another option would be to do:
typedef char Value
#define ace 1
#define jester 11
#define queen 12
#define king 13
This is essentially the same result but with this method it'll let me do:
Value a_value = 7;
Can I use the 2nd method with #define or it's the wrong way to do this?
Upvotes: 0
Views: 118
Reputation: 23
You may do like this
enum Value ={ace=1, two,...};
Value a_value = static_cast<Value>(some int value, in enum range);
Upvotes: 0
Reputation: 122383
In your example, I think the enum
solution is better, it prevents usage like:
Value a = 0; //illegal
Value b = 14; //illegal
Just fill in the blanks between ace
and jester
. That seems no harms. In my opinion, the code even looks cleaner:
enum Value{
ace = 1,
two,
three,
four,
five,
six,
seven,
eight,
nine,
ten,
jester,
queen,
king
};
Upvotes: 3