C va_start()

The va_start() is a macro defined in the stdarg.h header file. This macro helps to initialize the variable argument list pointed by 'ap'. This macro must called before va_arg() and va_end() macros.


void va_start(va_list ap, last_arg); #where ap is the object of va_list

 

va_start() Parameters: 

The va_start() function takes two parameters. The argument 'ap' holds the information required to retrieve the additional arguments with va_arg() macro.       

Parameter Description Required / Optional
ap the object of va_list and it will hold the information Required
last_arg last known fixed argument being passed Required

va_start() Return Value

The macro va_start() does not return any value it just initializes the variable argument list.


 

Examples of va_start()

Example 1: Working of va_start() function in C?


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

int getsum(int, ...);

int main(void) {
   printf("Sum of 20, 40 and 30 = %d\n",  getsum(3, 20, 40, 30) );
   printf("Sum of 10, 15, 5 and 20 = %d\n",  getsum(4,10, 15, 5, 20) );

   return 0;
}

int getsum(int num_args, ...) {
   int val = 0;
   va_list ap;
   int i;

   va_start(ap, num_args);
   for(i = 0; i < num_args; i++) {
      val += va_arg(ap, int);
   }
   va_end(ap);
 
   return val;
}

Output:


Sum of 20, 40 and 30 = 90
Sum of 10, 15, 5, 20 = 50

Example 2: How getdate() works in C?


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

int add_nums(int count, ...) 
{
    int result = 0;
    va_list args;
    va_start(args, count);
    for (int i = 0; i < count; ++i) {
        result += va_arg(args, int);
    }
    va_end(args);
    return result;
}
 
int main() 
{
   
     printf("Sum of 20, 10, 15, 40, 30 is :\n");
     add_nums(20, 10, 15, 40, 30);
}

Output:


Sum of 20, 10, 15, 40, 30 is :
115