Default values in a C Struct

前端 未结 10 1644
闹比i
闹比i 2020-11-29 16:59

I have a data structure like this:

    struct foo {
        int id;
        int route;
        int backup_route;
        int current_route;
    }

and a

10条回答
  •  没有蜡笔的小新
    2020-11-29 17:43

    You could address the problem with an X-Macro

    You would change your struct definition into:

    #define LIST_OF_foo_MEMBERS \
        X(int,id) \
        X(int,route) \
        X(int,backup_route) \
        X(int,current_route)
    
    
    #define X(type,name) type name;
    struct foo {
        LIST_OF_foo_MEMBERS 
    };
    #undef X
    

    And then you would be able to easily define a flexible function that sets all fields to dont_care.

    #define X(type,name) in->name = dont_care;    
    void setFooToDontCare(struct foo* in) {
        LIST_OF_foo_MEMBERS 
    }
    #undef X
    

    Following the discussion here, one could also define a default value in this way:

    #define X(name) dont_care,
    const struct foo foo_DONT_CARE = { LIST_OF_STRUCT_MEMBERS_foo };
    #undef X
    

    Which translates into:

    const struct foo foo_DONT_CARE = {dont_care, dont_care, dont_care, dont_care,};
    

    And use it as in hlovdal answer, with the advantage that here maintenance is easier, i.e. changing the number of struct members will automatically update foo_DONT_CARE. Note that the last "spurious" comma is acceptable.

    I first learned the concept of X-Macros when I had to address this problem.

    It is extremely flexible to new fields being added to the struct. If you have different data types, you could define different dont_care values depending on the data type: from here, you could take inspiration from the function used to print the values in the second example.

    If you are ok with an all int struct, then you could omit the data type from LIST_OF_foo_MEMBERS and simply change the X function of the struct definition into #define X(name) int name;

提交回复
热议问题