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 printf(char string, ...);
Int scanf(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. Inside the function, we take the pointer of the first argument. We can get the next argument by incrementing the pointer value. The following example show how we pass variable arguments to a function and how we parse each argument one by one.

int v_printf(int arg_count, ...)
{
  int* vl;
  int i_arg, i;

  vl = &arg_count;
  for(i = 0; i < arg_count; i++)
  {
    i_arg = *vl++;
    printf("Argument %d = %d\n", i, i_arg);
  }
  vl = NULL;


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

In the next question, we will discuss the variadic function and argument parsing using stdarg.h utility macros in a more managed way.

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

Fibonaci using recursion, Armstrong number, variadic functions, variadic macro, multiple arguments in printf and scanf, strcpy and strcat source, memcpy vs memmove, strrev 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