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.

About our authors: Team EQA

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

#