Default values in a C Struct

前端 未结 10 1635
闹比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:44

    While macros and/or functions (as already suggested) will work (and might have other positive effects (i.e. debug hooks)), they are more complex than needed. The simplest and possibly most elegant solution is to just define a constant that you use for variable initialisation:

    const struct foo FOO_DONT_CARE = { // or maybe FOO_DEFAULT or something
        dont_care, dont_care, dont_care, dont_care
    };
    ...
    struct foo bar = FOO_DONT_CARE;
    bar.id = 42;
    bar.current_route = new_route;
    update(&bar);
    

    This code has virtually no mental overhead of understanding the indirection, and it is very clear which fields in bar you set explicitly while (safely) ignoring those you do not set.

提交回复
热议问题