Is it a good idea to use varargs in a C API to set key value pairs?

前端 未结 7 2654
情书的邮戳
情书的邮戳 2021-02-20 11:47

I am writing an API that updates a LOT of different fields in a structure.

I could help the addition of future fields by making the update function variadic:

<         


        
7条回答
  •  猫巷女王i
    2021-02-20 12:29

    Why not have one arg, an array. Even better, a pointer to an array.

    struct field {
      int val;
      char* name;
    };
    

    or even...

    union datatype {
      int a;
      char b;
      double c;
      float f;
    // etc;
    }; 
    

    then

    struct field {
      datatype val;
      char* name;
    };
    
    union (struct* field_name_val_pairs, int len);
    

    ok 2 args. I lied, and thought a length param would be good.

提交回复
热议问题