Default values in a C Struct

前端 未结 10 1605
闹比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条回答
  •  -上瘾入骨i
    2020-11-29 17:17

    You can change your secret special value to 0, and exploit C's default structure-member semantics

    struct foo bar = { .id = 42, .current_route = new_route };
    update(&bar);
    

    will then pass 0 as members of bar unspecified in the initializer.

    Or you can create a macro that will do the default initialization for you:

    #define FOO_INIT(...) { .id = -1, .current_route = -1, .quux = -1, ## __VA_ARGS__ }
    
    struct foo bar = FOO_INIT( .id = 42, .current_route = new_route );
    update(&bar);
    

提交回复
热议问题