tags:

views:

72

answers:

2

I don't understand why this doesn't print out "this is a test 42" like I'm expecting it to?

  1 #include <stdio.h>
  2 #include <stdarg.h>
  3 
  4 #define ME(x)   blah x
  5 
  6 void blah(const char *fmt, ...)
  7 {
  8         va_list arg;
  9 
 10         va_start(arg, fmt);
 11         printf(fmt, arg);
 12         va_end(arg);
 13 }
 14 
 15 int main()
 16 {
 17         ME(("this is a test %d\n", 42));
 18 
 19         return 0;
 20 }

Instead it's something like this:

$ gcc blah.c
$ ./a.out
this is a test 1606416656 
+8  A: 

You want to call vprintf() instead of printf().

Uli Schlachter
Thank you very much! In the linux kernel, I'm assuming there is also vprintk?
Brian
Seems so, googling for "kernel vprintk" found this:http://lkml.indiana.edu/hypermail/linux/kernel/0407.3/1688.html
Uli Schlachter
+2  A: 

You should use va_arg to get the actual argument value. Va_start is only an initialization of the arg variable. Arg is actualy a pointer to the value on the stack, it's not the valut itself.

The following line gets the actual value:

int myvalue = va_arg(arg,int);

Notice that I get an int and not a short, since short's are automatically promoted to int by the C compiler.

EDIT: Uli's answer is also correct. If you want to pass multiple values to printf, you should call vprintf instead of printf (and then calling va_arg is not needed, since in this case you don't know the exact types of the arguments).

Patrick