Passing variable number of arguments around

前端 未结 11 626
我寻月下人不归
我寻月下人不归 2020-11-22 07:16

Say I have a C function which takes a variable number of arguments: How can I call another function which expects a variable number of arguments from inside of it, passing a

11条回答
  •  北海茫月
    2020-11-22 07:39

    I'm unsure if this works for all compilers, but it has worked so far for me.

    void inner_func(int &i)
    {
      va_list vars;
      va_start(vars, i);
      int j = va_arg(vars);
      va_end(vars); // Generally useless, but should be included.
    }
    
    void func(int i, ...)
    {
      inner_func(i);
    }
    

    You can add the ... to inner_func() if you want, but you don't need it. It works because va_start uses the address of the given variable as the start point. In this case, we are giving it a reference to a variable in func(). So it uses that address and reads the variables after that on the stack. The inner_func() function is reading from the stack address of func(). So it only works if both functions use the same stack segment.

    The va_start and va_arg macros will generally work if you give them any var as a starting point. So if you want you can pass pointers to other functions and use those too. You can make your own macros easily enough. All the macros do is typecast memory addresses. However making them work for all the compilers and calling conventions is annoying. So it's generally easier to use the ones that come with the compiler.

提交回复
热议问题