延长期限的常见做法是什么enum
在C语言中?我有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;
}
这不会编译出现“重复大小写值”错误,我理解这是因为abc
被视为第一个值,因此它最终会为不同的符号带来重复的整数值。
您唯一关心的是积分常数是否唯一。只需分配第二个元素的第一个元素enum
到第一个元素的最后一个元素enum
加一。
enum abc { A, B, C, };
enum def { D = C + 1, E, F };
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)