0

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Asics
  • 858
  • 1
  • 11
  • 20
  • possible duplicate of [Should I use #define, enum or const?](http://stackoverflow.com/questions/112433/should-i-use-define-enum-or-const) – P0W Sep 29 '13 at 05:41
  • I read the Should I use #define, enum or const? but it doesn't answer my question. My problem is more about having 'ugly' enums because I have to have every possibilities in the enum as to not cause type conflicts. – Asics Sep 29 '13 at 05:52

2 Answers2

3

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
};
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • I ended up defining everything in the enum. This isn't a big deal it just bothers me that I can't use numerical value for everything and constants only for special cases. I feel it'd make those special cases stand out more and ultimately make things more readable. – Asics Sep 29 '13 at 08:10
0

You may do like this

enum Value ={ace=1, two,...};
Value a_value = static_cast<Value>(some int value, in enum range);