C va_arg()

The va_arg() is a macro defined in the stdarg.h header file. This macro helps to get the next argument with type from the parameter list of the function. But this function cannot determine whether the retrieved argument is a last one or not.


type va_arg(va_list ap, type); #where ap is the object of va_list

 

va_arg() Parameters: 

The va_arg() function takes two parameters. The argument 'ap' holds the information required to retrieve the additional arguments with the state. In the initial call of va_start and before the first call of va_arg this 'ap' object is initialized.      

Parameter Description Required / Optional
ap the object of va_list and it will hold the information Required
type the type name is used as the type of the expression, this macro expands to Required

va_arg() Return Value

The macro va_arg() returns the next argument list with the type of expression. We can call the macro va_arg any number of times to retrieve arguments from the list.

Input Return Value
if parameters next argument list

 

Examples of va_arg()

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


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

int getsum(int, ...);

int main () {
   printf("Sum of 23 and 45 is %d\n",  getsum(2, 23, 45) );
   return 0;
}

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

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

Output:


Sum of 23 and 45 is 68

Example 2: How va_arg() works in C?


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

void runcode (int i, ...)
{
    va_list pntr;
    va_start(pntr, i);

    if (i == 0)
    {
        int n = va_arg(pntr, int);
        printf("%d\n", n);
    }
    else
    {
        char *s = va_arg(pntr, char*);
        printf("%s\n", s);
    }

    va_end(pntr);
}

int main()
{
    runcode(0, 0xFFFFFFFF); // 0xffffffff is not an int
    runcode(1, NULL);       // NULL is not a char*
}

Output:


-1

(null)