什么是在C语言中扩展enum的常见做法?我有来自其他头文件的enum,想要用几个值扩展它们。希望以下示例能为我所需内容提供直观的理解。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
enum abc { A, B, C, }; /* from some other include */
enum def { abc, D, E, F }; /* extend enum from other include */
struct thing_s {
enum def kind; /* use extended enum */
union {
unsigned n;
char c;
char *str;
} data;
};
void print_thing(struct thing_s *t) {
switch (t->kind) {
case A:
fprintf(stdout, "%ul\n", t->data.n);
break;
case B:
case C:
case D:
fprintf(stdout, "%s\n", t->data.str);
break;
case E:
case F:
fprintf(stdout, "%c\n", t->data.c);
break;
default:
assert(0);
}
}
int main(int argc, char *argv[]) {
struct thing_s t;
t.kind = A;
t.data.n = 1;
print_thing(&t);
return EXIT_SUCCESS;
}
这段代码无法编译,提示“重复的case值”错误,我理解是因为abc
被视为第一个值,所以不同符号最终会有重复的整数值。
void*
指向数据,并将其分配在结构体之外。 - Lundin