Jabez
Jabez

Reputation: 1943

Separate different types of arguments from va_list

I am trying to write a macro which gets the information and sends that information to another function by splitting the orginal va_list into string and another va_list spawned from the original one.

Below is my code.

Call to macro

/* Usage */
PRINT_LOG("Format log = %d, %f, %s", 1, 2.7, "Test");

My code below

/* my includes here */
#include <stdarg.h>

void printInfo(int level, const char *debugInfo, ...); /* defined in 3rd party API */

void formatLogs(int level, ...);

#define PRINT_LOG(...) formatLogs(0, __VA_ARGS__)

void formatLogs(int level, ...)
{
  va_list args;
  va_start(args, level);

  /* get the first argument from va_list */
  const char *debugString = va_arg(args, const char*);

  /* here I want to get the rest of the variable args received from PRINT_LOG*/
  va_list restOfArgs = ???????; /* restOfArgs should be 1, 2.7, "Test" */

  /* Below I want to send the rest of the arguments */
  printInfo(level, debugString, args);
  va_end(args);
}

Is it possible to send some part of va_list as va_list to another function?? If so, how can i do it?

Thank you very much in advance.

Upvotes: 1

Views: 1029

Answers (1)

Mark Benningfield
Mark Benningfield

Reputation: 2892

The simplest thing to do, based on the code in your question, is to redefine the macro like so:

#define PRINT_LOG(s, ...) printInfo(0, s, __VA_ARGS__)

and just skip the intermediate function altogether. Because what you're trying to do can't be done like that.

The , ...) variable argument ellipsis is not a va_list. The variable arguments passed to a function aren't realized as a va_list until va_start is invoked. To pass a va_list as a function argument, the function has to have a va_list in its signature, like this:

int vprintf(const char *format, va_list argList);

Upvotes: 2

Related Questions