Variable Arguments

Allows a variable number of arguments to be used, where they may not be initially known

 

Use <stdarg.h> header file to to provide macros and functions for variable arguments

 

The function takes an int as its first argument, followed by an ellipses (three dots ... )

 

Requires the following, defined in stdarg.h:

  • va_list type variable
  • va_macro to initialise va_list to the argument list
  • va_arg macro to access each argument in the argument list
  • va_end to clean up memory assigned to va_list
#include <stdio.h>
#include <stdarg.h>

double average(int someNum, ...) {	//note use of ellipses as 2nd argument

	va_list theArgs;		//somewhere to store the arguments
	double theSum = 0.0;		//ensure theSum is set to zero
	va_start(theArgs, someNum);	//initialise theArgs for someNum of arguments

	for (int i = 0; i < someNum; i++) { // access all the arguments assigned to theArgs
		theSum += va_arg(theArgs, int);
	}

	va_end(theArgs);		//clean theArgs from memory

	return theSum/someNum;
}

int main() {
	printf("Average of 2, 3, 4, 5, 6, 7, 8 = %f\n", average(7,2,3,4,5,6,7,8));
	int numArgs = 5;
	printf("Average of 2, 3, 4, 5 = %f\n", average(numArgs, 2,3,4,5,6,7,8));
	numArgs = 3;
	printf("Average of 5, 10, 15 = %f\n", average(numArgs, 5,10,15));
}

*Note:

  • In the 1st call of average() there is no space between the first argument, 7, and the data to be acted upon, and that it indicates the number of arguments to perform the function call upon.
  • In the 2nd & 3rd calls of average(), a variable has been used to perform this task.
  • In the 2nd call of average(), the same data set has been provided, but only acts upon the following number of arguments indicated in the numArgs variable, in this case 5 (instead of the above 7)

Compile & Run:

Average of 2, 3, 4, 5, 6, 7, 8 = 5.000000
Average of 2, 3, 4, 5 = 4.000000
Average of 5, 10, 15 = 10.000000

Leave a Reply