Anonymous union within struct not in c99?

后端 未结 7 1056
时光说笑
时光说笑 2020-11-28 11:40

here is very simplified code of problem I have:

enum node_type {
    t_int, t_double
};

struct int_node {
    int value;
};

struct double_node {
    double valu         


        
7条回答
  •  清歌不尽
    2020-11-28 12:05

    Another solution is to put the common header value (enum node_type type) into every structure, and make your top-level structure a union. It's not exactly "Don't Repeat Yourself", but it does avoid both anonymous unions and uncomfortable looking proxy values.

    enum node_type {
        t_int, t_double
    };
    struct int_node {
        enum node_type type;
        int value;
    };
    struct double_node {
        enum node_type type;
        double value;
    };
    union node {
        enum node_type type;
        struct int_node int_n;
        struct double_node double_n;
    };
    
    int main(void) {
        union node n;
        n.type = t_int; // or n.int_n.type = t_int;
        n.int_n.value = 10;
        return 0;
    }
    

提交回复
热议问题