Advertisement
charmonium

Implementing Variadic Functions

Jul 17th, 2018
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.32 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdarg.h>
  3.  
  4. size_t vmputs(size_t count, va_list arg_list);
  5.  
  6. // mputs ("multiple" puts)
  7. // like puts, but for multiple strings.
  8. size_t mputs(size_t count, ...) {
  9.     va_list arg_list;
  10.     va_start(arg_list, count);
  11.     size_t rc = vmputs(count, arg_list);
  12.     // I could implement this directly here
  13.     // but then I would be duplicating the code from vmputs
  14.     va_end(arg_list);
  15.     return rc;
  16. }
  17.  
  18. // as is convention
  19. // for every variadic function,
  20. // I have a second one prefixed with a 'v' that takes a va_args
  21. size_t vmputs(size_t count, va_list arg_list) {
  22.     size_t s = 0;
  23.     for(size_t i = 0; i < count; ++i) {
  24.         char* arg = va_arg(arg_list, char*);
  25.         s += puts(arg);
  26.     }
  27.     return s;
  28. }
  29.  
  30. // dbg_printf is like printf, but prepends "debug message: "
  31. // The "v" convention is found in most std functions
  32. // including the *printf family
  33. // so I can do things like this
  34. size_t dbg_printf(char* fmt, ...) {
  35.     size_t s = 0;
  36.     s += printf("debug message: ");
  37.  
  38.     // how do I pass all of my ... to printf??
  39.  
  40.     // use vprintf!
  41.     va_list arg_list;
  42.     va_start(arg_list, fmt);
  43.     s += vprintf(fmt, arg_list);
  44.     va_end(arg_list);
  45.  
  46.     return s;
  47. }
  48.  
  49. int main() {
  50.     mputs(3, "hello", "world", ".");
  51.  
  52.     dbg_printf("%d != %d\n", 3, 5);
  53.  
  54.     return 0;
  55. }
  56.  
  57. // Output:
  58. // hello
  59. // world
  60. // .
  61. // debug message: 3 != 5
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement