Functions like printf have a variable number of arguments, and users may want to define their own vararg functions.

Submitted by Gabriël Konat on 31 May 2013 at 12:15

On 1 June 2013 at 12:07 Daco Harkes commented:

Variable number of arguments is done in c with the va_list, explained in this tutorial tutorial.

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

/* this function will take the number of values to average
   followed by all of the numbers to average */
double average ( int num, ... )
{
	va_list arguments;                     
	double sum = 0;

	/* Initializing arguments to store all values after num */
	va_start ( arguments, num );           
	/* Sum all the inputs; we still rely on the function caller to tell us how
	 * many there are */
	for ( int x = 0; x < num; x++ )        
	{
		sum += va_arg ( arguments, double ); 
	}
	va_end ( arguments );                  // Cleans up the list

	return sum / num;                      
}

int main()
{
	/* this computes the average of 13.2, 22.3 and 4.5 (3 indicates the number of values to average) */
	printf( "%f\n", average ( 3, 12.2, 22.3, 4.5 ) );
	/* here it computes the average of the 5 values 3.3, 2.2, 1.1, 5.5 and 3.3
	printf( "%f\n", average ( 5, 3.3, 2.2, 1.1, 5.5, 3.3 ) );
}

This means only the first argument is type-checked, it is an int with the number of arguments. The argument types should be asserted inside the function or assume the types are correct.

Strictly spoken, the first argument is not required, the amount of arguments, this could be done in desugaring.

Proposed solution:

  1. allow the argument list to be (int a, …) or a normal argument list
  2. use va_list inside the function
  3. create an external module for stdarg with va_list, va_start, va_arg and va_end

On 1 June 2013 at 12:35 Gabriël Konat commented:

Looks like a good solution.

An extension would be to also allow typed variable arguments like in Java or C#, where you can say something like int function(int a, string b, params float[] rest). In C you would also need the length of the array so it might look like params float[size] rest. But untyped varargs are required anyway for compatibility with C.

Log in to post comments