tags:

views:

348

answers:

5

Possible Duplicate:
C Programming: Forward variable argument list.

What I'd like to do is send data to a logging library (that I can't modfify) in a printf kind of way.

So I'd like a function something like this:

void log_DEBUG(const char* fmt, ...) {
   char buff[SOME_PROPER_LENGTH];
   sprintf(buff, fmt, <varargs>);
   log(DEBUG, buff);
}

Can I pass varargs to another vararg function in some manner?

+2  A: 

Not in standard C++.

Richard Pennington
Right, in C++ it would be preferable to use `<<`
ezpz
+6  A: 

This is why you have the vprintf family of functions.

Nikolai N Fetissov
+4  A: 

For your specific requirement, you can use vsprintf. My C/C++ is too rusty to recall if there's a straightforward way to do it when the other function isn't designed for it (without getting into ugly stack manipulation), but I tend to think not.

T.J. Crowder
+4  A: 

You can send it to another function that takes a va_list as an argument. There is no other way, short of resorting to hand crafted asm, or doing some kind of horrifying guessing game to figure out the 'number' of parameters.

This would work:

void log_DEBUG(const char* fmt, ...)
{
  va_list va;
  va_start(va,fmt);
  char buff[blah];
  vsprintf(buff,fmt,va);
  log(DEBUG,buff);
  va_end(va);
}

Basically, whenever you write a function that takes ..., you should write another version that takes a va_list - its the polite thing to do if you want to enable this type of chaining call.

Chris Becke
Exactly what I needed. I was thinking maybe there was someway to pass the arg list directly, but vsprintf will do nicely!
gct
+1  A: 

Yes, you can -- sort of, and using nonstandard extensions. This is Windows/MSVC:

void mysprintf(char* out, const char* fmt, va_list args)
{
  // ... do something here
}


void log_DEBUG(const char* fmt, ...) {
   char buff[SOME_PROPER_LENGTH];
   va_list args;
   va_start(args, fmt);
   mysprintf(buff, fmt, args);
   va_end(args);
   log(DEBUG, buff);
}
John Dibling
Don't forget **va_end**
Nikolai N Fetissov
@Nikolai N Fetissov: Thanks, fixed.
John Dibling
I don't see anything non-standard here.
Steve Jessop
I thought that va_list was itself non-standard. Could be wrong.
John Dibling
Nope. The only thing in `stdarg.h` (or `cstdarg`) not part of C89 (and therefore C++) is `va_copy` which was added in C99.
Chris Lutz