Variable argument number in functions

  • Follow


Hello!

If I was to write a function that takes variable argument number that
would simply call printf with those exact arguments, how do I pass them to
printf?

E.g.

int my_printf (const char *fmt, ...)
  {
  printf ( ??????????? );
  }

Thanks,

Andrej
0
Reply andrej.prsa (18) 9/4/2003 9:17:39 AM

Andrej Prsa <andrej.prsa@guest.arnes.si> wrote:
> Hello!
> 
> If I was to write a function that takes variable argument number that
> would simply call printf with those exact arguments, how do I pass them to
> printf?
> 
> E.g.
> 
> int my_printf (const char *fmt, ...)
>  {
>  printf ( ??????????? );
>  }

That's what the vprintf() function is for:

#include <stdarg.h>

int my_printf(const char *fmt, ...)
{
    va_list ap;
    int r;

    va_start(ap, fmt);
    r = vprintf(fmt, ap);
    va_end(ap);

    return r;
}

....and so, you should also write a vmy_printf function, so that your
function can itself be wrapped in the same manner:

int vmy_printf(const char *fmt, va_list ap)
{
    /* Put whatever my_printf functionality you want here */
    return vprintf(fmt, ap);
}

int my_printf(const char *fmt, ...)
{
    va_list ap;
    int r;

    va_start(ap, fmt);
    r = vmy_printf(fmt, ap);
    va_end(ap);

    return r;
}

	- Kevin.

0
Reply Kevin 9/4/2003 9:40:57 AM


On Thu, 4 Sep 2003 11:17:39 +0200, Andrej Prsa wrote

> int my_printf (const char *fmt, ...)
>   {
>   printf ( ??????????? );
>   }

Through va_start() and its relatives. There is a precise example in K&R II -
pg.155, but if you don't have K&RII the algorithm is something like that :

* va_start(ap, fmt) /* ap points to the first unnamed argument */
* use va_arg to move forward to the next argument
* use va_end when you have finished

HTH
D. 

-- 
PGP key 39A40276 at wwwkeys.eu.pgp.net 
key fingeprint: 9A0B 61C6 B826 4B73 69BB  972B C5E7 A153 39A4 0276
0
Reply mandas (27) 9/4/2003 9:44:05 AM

Andrej Prsa <andrej.prsa@guest.arnes.si> writes:

> If I was to write a function that takes variable argument number that
> would simply call printf with those exact arguments, how do I pass them to
> printf?

If you had read the FAQ, you would already know.
-- 
"I don't have C&V for that handy, but I've got Dan Pop."
--E. Gibbons
0
Reply blp (3953) 9/4/2003 5:15:50 PM

3 Replies
35 Views

(page loaded in 0.079 seconds)

Similiar Articles:













7/2/2012 3:28:49 AM


Reply: