Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass variable number of arguments from one function to another?

Is there any way to directly pass a variable number of arguments from one function to another?

I'd like to achieve a minimal solution like the following:

int func1(string param1, ...){
  int status = STATUS_1;
  func2(status, param1, ...);
}

I know I can do this using something like the following, but this code is going to be duplicated multiple times so I'd like to keep it as minimalist as possible while also keeping the function call very short

int func1(string param1, ...){
  int status = STATUS_1;
  va_list args;
  va_start(args, param1);
  func2(status, param1, args);
  va_end(args);
}

Thanks!

like image 464
Zain Rizvi Avatar asked Dec 29 '22 07:12

Zain Rizvi


2 Answers

No, you have to pass the varargs using a va_list as per your second example.

It's just 3 lines extra code, if you want to avoid duplicating those lines, and func2 is always the same, or atleast takes the same parameters, make a macro out of it.

#define CALL_MY_VA_FUNC(func,param) do {\
        va_list args; \
        va_start(args,param);\
        func(param,param,args);\
        va_end(args); } while(0)
like image 137
nos Avatar answered Jan 25 '23 15:01

nos


Just pass args as a parameter of type va_list to func2

like image 43
Brian R. Bondy Avatar answered Jan 25 '23 15:01

Brian R. Bondy