Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

va_list in C: Creating a function that doesn't need a argument count like 'printf'

Using the <stdarg.h> header, one can make a function that has a variable number of arguments, but:

  1. To start using a va_list, you need to use a va_start macro that needs to know how many arguments there, but the printf & ... that are using va_list don't need the argument count. How can I create a function that doesn't need the argument count like printf?

  2. Let's say I want to create a function that takes a va_list and instead of using it, passes it to another function that requires a va_list? (so in pseudocode, it would be like void printfRipOff(const char* format, ...) {printf(format, ...);})

like image 340
KianFakheriAghdam Avatar asked Sep 02 '25 09:09

KianFakheriAghdam


1 Answers

Let's say I want to create a function that takes a va_list and instead of using it, passes it to another function that requires a va_list?

Look at function vprintf( const char * format, va_list arg ); for one example of a function that takes a va_list as an input parameter.

It is basically used this way:

#include <stdio.h>
#include <stdarg.h>

void CountingPrintf(const char* format, ...)
{
   static int counter = 1;
   printf("Line # %d: ", counter++); // Print a Counter up front

   va_list args;
   va_start(args, format); // Get the args
   vprintf(format, args);  // Pass the "args" through to another printf function.

   va_end(args);
}

int main(void) {
    CountingPrintf("%s %s\n", "Hello", "World");
    CountingPrintf("%d + %d == %d\n", 2, 3, 2+3);
    
    return 0;
}

Output:

Line # 1: Hello World
Line # 2: 2 + 3 == 5
like image 118
abelenky Avatar answered Sep 05 '25 00:09

abelenky