Default values in a C Struct

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

    How about something like:

    struct foo bar;
    update(init_id(42, init_dont_care(&bar)));
    

    with:

    struct foo* init_dont_care(struct foo* bar) {
      bar->id = dont_care;
      bar->route = dont_care;
      bar->backup_route = dont_care;
      bar->current_route = dont_care;
      return bar;
    }
    

    and:

    struct foo* init_id(int id, struct foo* bar) {
      bar->id = id;
      return bar;
    }
    

    and correspondingly:

    struct foo* init_route(int route, struct foo* bar);
    struct foo* init_backup_route(int backup_route, struct foo* bar);
    struct foo* init_current_route(int current_route, struct foo* bar);
    

    In C++, a similar pattern has a name which I don't remember just now.

    EDIT: It's called the Named Parameter Idiom.

提交回复
热议问题