Variable Arguments in C Programming

In situations, where you may need to write a function that can take unknown number of arguments (parameters) instead of predefined number, you'll need to include stdarg.h header file in your C program which provides the functionality and macros to implement such variable arguments.

Syntax :

functionName(int, ... )

Such function must have its last argument defined as ellipses(...), and the first one must be an integer which defines the total number of variable arguments passed. You must create a va_list type variable in the function definition. Use va_start macro to initialize the va_list variable to an argument list and va_arg macro and va_list variable to access each item in argument list. Use va_end macro to clean up the memory assigned to va_list variable at the end.

Example :

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

float findAverage(int num,...)
{

  va_list data;
  float sum = 0.0;
  int i;

  /* initialize data for number of arguments */
  va_start(data, num);

  /* access all the arguments assigned to data */
  for (i = 0; i < num; i++) {
    sum += va_arg(data, int);
  }

  /* clean memory reserved for data */
  va_end(data);

  return sum/num;
}

int main() {
  printf("Average of 1, 2, 3, 4, 5, 6, 7, 8, 9 and 10 is : %f\n", findAverage(10,1,2,3,4,5,6,7,8,9,10));
  return 0;
}
	

0 Like 0 Dislike 0 Comment Share

Leave a comment