如何检查switch语句表达式中的struct数据值

时间:2014-06-16 07:54:10

标签: c struct switch-statement

我的代码:

#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;
  }
}

我想通过区分值0x01和0x02来检查struct中保存的值,但是我在形成上面显示的switch语句时遇到了问题。我尝试过cards.uint8_t IDeecollcards[qty] EEMEM,但会产生以下错误:

error: excepted expression before struct...

我知道cards只是一个类型的名称而不是变量。 0x01表示ID类型的uint8_t变量,其余十六进制值用于初始化tagbyte[5]数组。

2 个答案:

答案 0 :(得分:3)

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;
}

我删除了EEMEM,否则它不会在我的系统上编译

答案 1 :(得分:1)

EEMEM只是告诉编译器存储数据的位置(显然在EEPROM中......)。要从中读取,只需使用变量名称和索引(这将遍历所有元素):

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