Default values in a C Struct

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

    Perhaps consider using a preprocessor macro definition instead:

    #define UPDATE_ID(instance, id)  ({ (instance)->id= (id); })
    #define UPDATE_ROUTE(instance, route)  ({ (instance)->route = (route); })
    #define UPDATE_BACKUP_ROUTE(instance, route)  ({ (instance)->backup_route = (route); })
    #define UPDATE_CURRENT_ROUTE(instance, route)  ({ (instance)->current_route = (route); })
    

    If your instance of (struct foo) is global, then you don't need the parameter for that of course. But I'm assuming you probably have more than one instance. Using the ({ ... }) block is a GNU-ism that that applies to GCC; it is a nice (safe) way to keep lines together as a block. If you later need to add more to the macros, such as range validation checking, you won't have to worry about breaking things like if/else statements and so forth.

    This is what I would do, based upon the requirements you indicated. Situations like this are one of the reasons that I started using python a lot; handling default parameters and such becomes a lot simpler than it ever is with C. (I guess that's a python plug, sorry ;-)

提交回复
热议问题