Variable Length Function in C

In C programming language function has a wide impact. In function there is a feature and that is variable length functions. In this article we will know about these topics included in variable length function.

  • What is variable length function
  • minimum of given numbers
  • average of given numbers
  • Macros

So, let’s get started……

What is Variable Length Function

It allows a function that will receive any number of arguments in it. There are some situations where we need this feature. We have to deal with a number of arguments in the below. We are using some codes shown below :

Example of minimum of given numbers :

// C program to demonstrate use of variable 
// number of arguments. 
#include <stdarg.h> 
#include <stdio.h> 

// this function returns minimum of integer 
// numbers passed. First argument is count 
// of numbers. 
int min(int arg_count, ...) 
{ 
	int i; 
	int min, a; 

	// va_list is a type to hold information about 
	// variable arguments 
	va_list ap; 

	// va_start must be called before accessing 
	// variable argument list 
	va_start(ap, arg_count); 

	// Now arguments can be accessed one by one 
	// using va_arg macro. Initialize min as first 
	// argument in list 
	min = va_arg(ap, int); 

	// traverse rest of the arguments to find out minimum 
	for (i = 2; i <= arg_count; i++) 
		if ((a = va_arg(ap, int)) < min) 
			min = a; 

	// va_end should be executed before the function 
	// returns whenever va_start has been previously 
	// used in that function 
	va_end(ap); 

	return min; 
} 

// Driver code 
int main() 
{ 
	int count = 5; 
	printf("Minimum value is %d", min(count, 12, 67, 6, 7, 100)); 
	return 0; 
} 

The output of the above code is given below :

Minimum value is 6

Example of average of given numbers :

// C program to demonstrate working of 
// variable arguments to find average 
// of multiple numbers. 
#include <stdarg.h> 
#include <stdio.h> 

int average(int num, ...) 
{ 
	v_list vlist; 

	int sum = 0, i; 

	v_start(vlist, num); 
	for (i = 0; i < num; i++) 
		sum += v_arg(vlist, int); 

	v_end(vlist); 

	return sum / num; 
} 

// Driver code 
int main() 
{ 
	printf("Average of {2, 3, 4} = %d\n", 
						average(2, 3, 4)); 
	printf("Average of {3, 5, 10, 15} = %d\n", 
					average(3, 5, 10, 15)); 
	return 0; 
} 

The output of the above code is given below :

Average of {2, 3, 4} =3
Average of {3, 5, 10, 15} =10

Macros in Argument

In order to implement the functionality of the variable arguments we need macros.

  • Here we use int parameter and v_start macro to initialize the v_list variable to an argument list. The macro v_start is defined in stdarg.h header file.
  • We also use v_arg macro and vlist variable to access each item in argument list
  • The macro v_end to clean up the memory assigned to v_list variable.
Design a site like this with WordPress.com
Get started