gpt4 book ai didi

c - typedef 枚举 : Different values for one member

转载 作者:行者123 更新时间:2023-12-02 09:11:34 25 4
gpt4 key购买 nike

我想知道是否可以为 typedef 枚举的同一成员分配不同的值,如下所示......:

typedef enum {

START = 0x01,
DATA = 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
CRC = 0x0A, 0x0B

}bytes_t;

...所以我以后可以像这样使用它:

bytesReceived++;                        // incremented for every received byte

switch (bytesReceived) {

case START:
dPkg->startByte = dpkgRxBuffer[bytesReceived];
break;

case DATA:
dPkg->data = dpkgRxBuffer[bytesReceived];
break;

case CRC:
dPkg->crc = dpkgRxBuffer[bytesReceived];
break;

}

因此,如果在循环中调用,程序将执行DATA 情况八次。这有效吗?这只是第一个想法,因此遗憾的是我无法为您提供更多背景信息。

最佳答案

这是不可能的。枚举是一个具有不同值的常量。
使用多个案例:

typedef enum {
START = 0x01,
DATA_2 = 0x02,
DATA_3 = 0x03,
DATA_4 = 0x04,
...
DATA_9 = 0x09,
CRC_1 = 0x0A,
CRC_2 = 0x0B
}bytes_t;

switch (variable) {
case START:
dPkg->startByte = dpkgRxBuffer[bytesReceived];
break;
case DATA_2:
case DATA_3:
...
case DATA_9:
dPkg->data = dpkgRxBuffer[bytesReceived];
break;
case CRC_1:
case CRC_2:
dPkg->crc = dpkgRxBuffer[bytesReceived];
break;
}

或使用 if 与范围:

typedef enum {
START = 0x01,
DATA_START = 0x02,
DATA_STOP = 0x09,
CRC_1 = 0x0A,
CRC_2 = 0x0B
}bytes_t;

if (variable == START) {
dPkg->startByte = dpkgRxBuffer[bytesReceived];
} else if (DATA_START <= variable && variable <= DATA_STOP) {
dPkg->data = dpkgRxBuffer[bytesReceived];
} else if (variable == CRC_1 || variable == CRC_2) {
dPkg->crc = dpkgRxBuffer[bytesReceived];
}

关于c - typedef 枚举 : Different values for one member,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51442668/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com