gpt4 book ai didi

c - 开关盒中的枚举

转载 作者:太空狗 更新时间:2023-10-29 15:33:25 26 4
gpt4 key购买 nike

这段代码有什么问题:

#define str(x) #x
#define xstr(x) str(x)


typedef unsigned char uint8_t;
typedef enum
{

RED = 0x64,
GREEN = 0x65,
/* other enum values */
BLUE = 0x87

} Format;

char buffer[50];

/* other code and variables */

/* somewhere later in code */

myformat = RED;
/* later calling format function */

MapFormattToString(myformat,&buffer);


void MapFormattToString(uint8_t format,char *buffer)
{
printf("format = %x\n",format); /*format printf has output 64 */
switch(format)
{
case RED:
sprintf(buffer,"%s\n", xstr(RED));
break;
case GREEN:
sprintf(buffer,"%s\n", xstr(GREEN));
break;
case BLUE:
sprintf(buffer,"%s\n", xstr(BLUE));
break;
default:
sprintf(buffer,"Unsupported color\n");
}
}

如果我使用 myformat = RED 单步执行此函数,它不会通过任何案例,而是通过切换案例中的默认值。
我的目标是缓冲区中应该有 RED 而不是相应的枚举值,即 64。

编译器:Windows XP 上的 gcc 3.4.5

最佳答案

我刚写了下面的程序,编译,测试,输出结果是:

$ ./test
d
e

$

这正是您所期望的。希望这可以帮助您发现程序中的一些差异。

#include<stdio.h>

typedef unsigned char uint8_t;

typedef enum {
RED = 0x64,
GREEN = 0x65,
BLUE = 0x87
} Format;

void MapFormatToString(uint8_t format, char *buffer) {
switch (format) {
case RED:
sprintf(buffer, "%c\n", RED);
break;
case GREEN:
sprintf(buffer, "%c\n", GREEN);
break;
case BLUE:
sprintf(buffer, "%c\n", BLUE);
break;
default:
sprintf(buffer, "Unknown\n");
}

}

main (int argc, char *argv[]) {
char buffer[100];

MapFormatToString(RED, buffer);
printf(buffer);
MapFormatToString(GREEN, buffer);
printf(buffer);
MapFormatToString(BLUE, buffer);
printf(buffer);
}

关于c - 开关盒中的枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10801152/

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