Variable Arguments in C-Language

 

Variable Arguments in  C-Language

Variable Arguments

  • Variable length argument is a feature that allows a function to receive any number of arguments.
  • There are situations where we want a function to handle variable number of arguments according to requirement.
  1.  Sum of given numbers.
  2.  Minimum of given numbers. and many more.
Variable number of arguments are represented by three dotes (…)
Syntax:
    datatype functionname(datatype,...)
    {
    ...
    ...
    }
    
    void main()
    {
    functionname(v1,v2,v3);
    functionname(v1,v2,v3,v4,v5);
    }
/* C Variable Length Arguments - This program
 * demonstrates variable length arguments in C
 */

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

int avg(int num, ...)
{
	va_list valist;
	int sum = 0;
	int i;

	// initializing valist for num number of arguments
	va_start(valist, num);

	// now accessing all the arguments that is assigned to valist
	for(i=0; i<num; i++)
	{
		sum = sum + va_arg(valist, int);
	}

	// now cleaning the memory reserved for the valist
	va_end(valist);

	return sum/num;
}

void main()
{
	int num1=10, num2=20, num3=30;
	clrscr();

	printf("The average is %d", avg(3, num1, num2, num3));

	getch();
}

Output:
The average is 20




No comments:

Post a Comment