Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend enum with additional values

Tags:

c

enums

What is the common practice for extending an enum in C? I have enums 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.

like image 937
Rorschach Avatar asked May 16 '18 03:05

Rorschach


1 Answers

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 }; 
like image 66
DeiDei Avatar answered Oct 03 '22 20:10

DeiDei