Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing and using variable number of arguments to function in C

Tags:

c

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 
like image 374
Brian Avatar asked Dec 22 '22 23:12

Brian


1 Answers

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

like image 62
Uli Schlachter Avatar answered Mar 01 '23 22:03

Uli Schlachter