Reputation: 32416
What is the common practice for extending an enum
in C? I have enum
s from other includes and would like to extend them with a few values. Hopefully, the following example provides the intuition for what I would like to achieve.
#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;
}
This doesn't compile with "duplicate case value" errors, which I understand because abc
is being treated as the first value so it ends up with duplicate integer values for the different symbols.
Upvotes: 7
Views: 5128
Reputation: 10415
Your only concern is for the integral constants to be unique. Simply assign the first element of your second enum
to the last element of your first enum
plus one.
enum abc { A, B, C, };
enum def { D = C + 1, E, F };
Upvotes: 7