user3743943
user3743943

Reputation: 27

How to check struct data value in a switch statement expression

My code:

#define qty     2
typedef struct { uint8_t ID;
                 uint8_t tagbyte[5];  
               } cards;

const cards eecollcards[qty] EEMEM ={
                                      {0x01, {0x2A, 0x00, 0x24, 0x91, 0xFD}},
                                      {0x02, {0x4F, 0x00, 0x88, 0x59, 0xB0}},
                                    };
int main (void)
while (1)
{
  switch (<what goes here?>)
  {
    case 0x01: .....
      break;
    case 0x02: .....
      break;
  }
}

I want to check values held in a struct by differentiating between the values 0x01 and 0x02, but I have problems forming the switch statement shown above. I have tried cards.uint8_t ID and eecollcards[qty] EEMEM but these generate errors such as the following:

error: excepted expression before struct...

I know that cards is just a name of a type and not a variable. 0x01 refers to the ID variable of type uint8_t and the remaining hex values are for initialization of the tagbyte[5] array.

Upvotes: 3

Views: 116

Answers (2)

Bart Friederichs
Bart Friederichs

Reputation: 33533

EEMEM just tells the compiler where to store your data (apparently in EEPROM...). To read from it, you just use the variables name and an index (this will loop over all elements):

int i = 0;
while (i < qty) {
  switch (eecollcards[i].ID) {
  ...
  }
  i++;
}

Upvotes: 1

mch
mch

Reputation: 9814

int main()
{
  int i;
  const cards eecollcards[qty] ={
                                {0x01, {0x2A, 0x00, 0x24, 0x91, 0xFD}},
                                {0x02, {0x4F, 0x00, 0x88, 0x59, 0xB0}},
                                };
  for (i = 0; i < qty; i++)
  {
    switch(eecollcards[i].ID)
    {
      case 0x01: //.....
        break;
      case 0x02: //.....
        break;
    }
  }
  return 0;
}

I removed the EEMEM, otherwise it wouldn't compile on my system

Upvotes: 3

Related Questions