4

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 

2 Answers 2

8

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

Sign up to request clarification or add additional context in comments.

2 Comments

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

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.