C/C++ language supports variable argument function or variadic function. The prototype defines a single defined argument along with undefined number of arguments.

Prototype Syntax:
Int v_printf(char string, ...);
The three dots indicate the functions can take more than one/many arguments.

Argument parsing: Arguments are pushed in the stack from right to left one by one. Each argument takes a size of integer in stack. For data types whose sizes are greater than integer, double or multiples of integer size are taken.

Code Example:
int v_printf(int arg_count, ...)
  va_list vl;
  int i_arg, i;

  va_start( vl, arg_count );
  for(i = 0; i < arg_count; i++)
    i_arg = va_arg( vl, int );
    printf("Argument %d = %d\n", i, i_arg);

  return 0;
int main(int argc, char *argv[])
  v_printf(2, 1, 2);
  return 0;

Inside the function, we take the va_list and initialize with the first argument. va_start() macro takes the address of the first argument and advances itself to the next argument. Now with each iteration we call va_arg() which actually returns the value of the current type and the pointer to the next argument. In this way we get the value of each argument and the va_list pointer advances to the next argument.

Macros are defined as:
#define va_start(ap,v)  ( ap = (va_list)&v + _INTSIZEOF(v) )
#define va_arg(ap,t)    ( *(t *)((ap += _INTSIZEOF(t)) - _INTSIZEOF(t)) )
#define va_end(ap)      ( ap = (va_list)0 )

You have viewed 1 page out of 248. Your C learning is 0.00% complete. Login to check your learning progress.

 Vote 0

Similar topics related to this section

Recursion, factorial using recursion, Fibonaci using recursion, Armstrong number, variadic functions, variadic macro, multiple arguments in printf and scanf, strcpy and strcat source,

# C Programming Language (Prentice Hall Software)
# Let Us C Paperback - 2006 by Yashavant Kanetkar
# Understanding and Using C Pointers Core techniques for memory management
# Data Structures Using C and C++ Paperback - 1998
# Data Structures In C Paperback - August 11, 2008 by Noel Kalicharan