cpointersrelational-operators

Invalid to compare similar data types?


I was working on a project of an application to find the probability of winning in a game of Texas Hold'em.

My program has 3 data types given below.

typedef enum {
  SPADES,
  HEARTS,
  DIAMONDS,
  CLUBS,
  NUM_SUITS
} suit_t;

struct card_tag {
  unsigned value;
  suit_t suit;
};
typedef struct card_tag card_t;

struct deck_tag {
      card_t ** cards;
        size_t n_cards;
};
typedef struct deck_tag deck_t;

I faced an issue when I was coding the assert function to check if the cards are repeated after shuffling. The error says I am comparing invalid data types. The image of the error message is:

Error Message

So technically I am still comparing similar datatypes, but they are invalid. Can anyone help me?


Solution

  • You cannot use == to compare two structures. Operands of == must be arithmetic or pointers. Compare their members instead:

    card_t a = card_from_num(checkingCard);
    card_t b = *d->cards[i];
    if (a.value == b.value && a.suit == b.suit) …
    

    You can write a function for this:

    _Bool CardsAreEqual(card_t a, card_t b)
    {
        return a.value == b.value && a.suit == b.suit;
    }
    …
    if (CardsAreEqual(card_from_num(checkingCard), *d->cards[i]) …