Nesting variadic functions

B

Boltar

Hi

Is it possible to nest variadic functions? Eg to do something like
this:

void mainfunc(char *fmt, ...)
{
va_list args;
va_start(args,fmt);

do something;

subfunc(fmt, args);
va_end(args);
}



void subfunc(char *fmt, ...)
{
va_list args;

va_start(args,fmt);
etc
va_end(args);
}


The above type of code will compile but the arguments in subfunc() are
corrupted. Is there a way to do this?

Thanks for any help

B2003
 
R

Richard Heathfield

Boltar said:
Hi

Is it possible to nest variadic functions? Eg to do something like
this:

void mainfunc(char *fmt, ...)
{
va_list args;
va_start(args,fmt);

do something;

subfunc(fmt, args);
va_end(args);
}



void subfunc(char *fmt, ...)

Oh, and you were doing so well.

void subfunc(char *fmt, va_list args)
{
va_list args;

Drop this...
va_start(args,fmt);

....and this...
etc
va_end(args);

....and this, and let the caller's va_end take the strain. (In the caller,
don't call va_args after calling subfunc - or, if you must, you'll first
have to call va_end and va_start again.)
 
B

Boltar

Boltar said:











Oh, and you were doing so well.

void subfunc(char *fmt, va_list args)


Drop this...




...and this...


...and this, and let the caller's va_end take the strain. (In the caller,
don't call va_args after calling subfunc - or, if you must, you'll first
have to call va_end and va_start again.)

Works nicely. Thanks.

B2003
 
R

Richard Tobin

Boltar said:
Is it possible to nest variadic functions? Eg to do something like
this:

Unfortunately C doesn't have the equivalent of Lisp's "apply".

Look at the printf() family of functions. In particular observe how
for each function there is a "v" version, that takes a va_list instead
of multiple arguments. You may find it useful to do the same for all
your variadic functions - not just the internal ones - to make it
convenient for others to write wrappers around them.

-- Richard
 
C

CBFalconer

Boltar said:
Is it possible to nest variadic functions? Eg to do something like
this:

void mainfunc(char *fmt, ...) {
va_list args;

va_start(args,fmt);
do something;
subfunc(fmt, args);
va_end(args);
}

void subfunc(char *fmt, ...) {
va_list args;

va_start(args,fmt);
etc
va_end(args);
}

The above type of code will compile but the arguments in subfunc()
are corrupted. Is there a way to do this?

Define the parameter as "const char *fmt". Maybe 'do something' or
subfunct() is altering *fmt? (or fmt). It looks like O(n * n)
where n is the number of arguments.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top