what are va_ macros in C ?

Can anybody plz give me some information on the va_ macros in C  ?

Thanks !
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

MercantilumConnect With a Mentor Commented:
You use va_ macros when you need to provide a variable number of arguments to a function.
E.g. printf(...);
Please have a look at
ankuratvbConnect With a Mentor Commented:
 va_arg, va_end, va_start       <STDARG.H>

 Macros that implement variable argument lists

   void va_start(va_list ap, lastfix);
   type va_arg(va_list ap, type);
   void va_end(va_list ap);

Some C functions, such as vfprintf and vprintf, take variable argument lists
in addition to taking a number of fixed (known) parameters.

The va_arg, va_end, and va_start macros provide a portable way to access
these argument lists.

 va_start sets ap to point to the first of the variable arguments being
passed to the function.

 va_arg expands to an expression that has the same type and value as the
next argument being passed (one of the variable arguments).

Because of default promotions, you can't use char, unsigned char, or float
types with va_arg.

 va_end helps the called function perform a normal return.

Argument ³ What It Is/Does

  ap       Points to the va_list variable argument list being passed to
             the function.
             The ap to va_arg should be the same ap that va_start
             NOTE: va_end might modify ap in such a way that it can't be
             used unless va_start is recalled.
  lastfix  The name of the last fixed parameter being passed to the
       called function.
  type      Used by va_arg to perform the dereference and to locate the
           following item.

You use these macros to step through a list of arguments when the called
function does not know the number and types of the arguments being passed.

 Calling Order

va_start must be used before the first call to va_arg or va_end.

va_end should be called after va_arg has read all the arguments. Failure to
do so might cause strange, undefined behavior in your program.

 Stepping Through the Argument List

The first time va_arg is used, it returns the first argument in the list.

Each successive time va_arg is used, it returns the next argument in the

It does this by first dereferencing ap, then incrementing ap to point to the
next item.

 Return Value:
va_start and va_end return no values.

va_arg returns the current argument in the list (the one that ap is pointing
Here is an example:

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

/* calculate sum of a 0 terminated list */
void sum(char *msg, ...)
   int total = 0;
   va_list ap;
   int arg;
   va_start(ap, msg);
   while ((arg = va_arg(ap,int)) != 0) {
      total += arg;
   printf(msg, total);

int main(void) {
   sum("The total of 1+2+3+4 is %d\n", 1,2,3,4,0);
   return 0;
All Courses

From novice to tech pro — start learning today.