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

前端 未结 7 2632
情书的邮戳
情书的邮戳 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条回答
  •  后悔当初
    2021-02-20 12:23

    The reasons given thus far for avoiding varargs are all good. Let me add another one that was not given yet, as it is less important, but can be encountered. The vararg mandates that the parameter be passed on the stack, thus slowing the function call. On some architecture the difference can be significative. On x86 it's not very important because of its lack of register, on SPARC, for example, it can be important. Up to 5 parameters are passed on registers and if your function uses few locals, no stack adjustment is made. If your function is a leaf function (i.e. doesn't call another function), there is no window adjustment also. The cost of the call is therefor very small. With a vararg, the normal sequence of passing parameters on the stack, stack adjustement and window management is made or your function wouldn't be able to get at the parameters. This increases the cost of the call significantly.

提交回复
热议问题