Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Other (better) way to define this type?

Status
Not open for further replies.

sedawk

Programmer
Feb 5, 2002
247
US
Hi There,

Is there other better way to define a new type for a mixture of integer and character? e.g., if I want to define a card rank which has 1,2,3,...,10 and then A,Q,J,K. I think I have to use union.

Code:
struct {
     int num;
     char letter;
} CardRank;

Is there any other (maybe better or simpler) ways? Just want to kown how others think about this.
 
Any number of ways are possible

Here's one example
Code:
typedef enum {
    ace, two, three, four,
    five, six, seven, eight,
    nine, ten, jack, queen,
    king
} face_t;

typedef enum {
    hearts, clubs, diamonds, spades
} suit_t;

typedef struct {
    face_t  face;
    suit_t  suit;
} card_t;

--
 
face_t is then all int, right? It is supposed to have int and char. Ok, anyway, this one counts. Anything else?
 
I think a union is useless (or redundant) in that case. In C char and int are both integral types. In that sense a simple char (or int) type is adequate for values between '0' and 'Z'. In C we can't define ++ etc ops, so you can't write a simple ++cardrank, but with union or structures (or enums) you can't do that too. This assignment saves cards order, you may compare its directly.

May be the simplest solution is to define int range 0..N for ranks and to define a function for CardRank letter (by number) for interface needs...
 
Why not just an int in the range 0 to 51 (or 0 to 55 if you are using the older European playing cards). The suit is n/13 and the face value index is n%13 (14 for the older cards). That way, if you are shuffling or attempting the get the ranking in bridge, you don't have to write any new comparison operators since they are all integers.
 
Everything is true except one thing: if need to combine with card suit, integer is not good enough, especially when displaying: 10A short for 10 Ace. or JA (note not 11A), etc. If ranks are in integers, one more step needed for integer, eg., 10 or char, eg., J.
 
So
Code:
char *face_names[] = { "ace", "two", };
Just index the array with your enumeration or modulus result.

--
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top