C question

Feb 01, 2007 3 Replies

Is there a way to pass an open list of parameters to a function?



Such as:



void channel_printf(const u8 *fmt, ...) {



OpenChannel();



va_list ap;



va_start(ap, fmt);



printf(fmt, ap); // It does not work that way



va_end(ap);



CloseChannel(); }



VLV


For some insight into just how terrifying this problem is,

Quote: "The horror. The horror."

Nevertheless, it's done a lot. Perl, for example, uses it in the Win32Ole module to call COM functions. It's generally a case of passing more arguments than are needed:

int (*func)(...) = something; int p[10]; get_param_values(p); func(p[0], p[1], p[2], p[3], ...);

It doesn't handle every case, but for particular compilers and sets of compile flags, it works ok. You need to check the rules for register passing and parameter alignment in the stack to know whether it'll work for you.

But what the OP wanted was to know of the existence of vprintf:

#include

my_printf(char* fmt, ...) { va_alist ap; int count;

va_start(ap, fmt); count = vprintf(fmt, ap) va_end(ap); return count; }

There's a vsprintf also, and others. Beware, some vsprintf's return a count, some a pointer.

Clifford Heath.

Use vprintf instead of printf.

Laurent

Join the Discussion

Have something to add? Share your thoughts — no account required.

Didn't find your answer?

Ask the community — no account required