Easy Tutorial
❮ C Exercise Example60 C Examples Printf Helloworld ❯

C Library Macro - va_start()

C Standard Library - <stdarg.h>

Description

The C library macro void vastart(valist ap, lastarg) initializes ap variable, which is used with the vaarg and vaend macros. lastarg is the last known fixed argument passed to the function, i.e., the argument before the ellipsis.

This macro must be called before using vaarg and vaend.

Declaration

Here is the declaration for the va_start() macro.

void va_start(va_list ap, last_arg);

Parameters

Return Value

NA

Example

The following example demonstrates the usage of the va_start() macro.

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

int sum(int, ...);

int main(void)
{
   printf("Sum of 10, 20, and 30 = %d\n",  sum(3, 10, 20, 30) );
   printf("Sum of 4, 20, 25, and 30 = %d\n",  sum(4, 4, 20, 25, 30) );

   return 0;
}

int sum(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;
}

Let's compile and run the above program, which will produce the following result:

Sum of 10, 20, and 30 = 60
Sum of 4, 20, 25, and 30 = 79

C Standard Library - <stdarg.h>

❮ C Exercise Example60 C Examples Printf Helloworld ❯