The number of arguments in a function call need not be same every time a function is called. In C language it is possible to call a function with varying number of arguments.
<stdarg.h> header file defines three functions va_arg, va_start and va_end to work with the varying number of arguments in a function call. It also declares a data-type called va_list.
The following C program shows how to call a function min() with varying list of arguments. The first argument in the list is the number of arguments in the function call.
//Program to find minimum number in a list of arguments
#include<stdio.h>
#include<stdarg.h>
#include<conio.h>
#include<limits.h>
int min(int cnt,...)
{
va_list valist;
int i,n,min=INT_MAX;
va_start(valist,cnt);
printf("\nArguments in the function call\n");
for(i=0;i<cnt;i++)
{
n=va_arg(valist,int);
printf("%d ",n);
if (n<min)
min=n;
}
va_end(valist);
return min;
}
main()
{
clrscr();
printf("\nThe smallest number in the list is %d\n",min(6,90,35,2,68,108,18));
printf("\nThe smallest number in the list is %d\n",min(10,6,5,7,-5,100,30,25,0,1,10));
getch();
}
/*
OUTPUT
-------
Arguments in the function call
90 35 2 68 108 18
The smallest number in the list is 2
Arguments in the function call
6 5 7 -5 100 30 25 0 1 10
The smallest number in the list is -5
*/
<stdarg.h> header file defines three functions va_arg, va_start and va_end to work with the varying number of arguments in a function call. It also declares a data-type called va_list.
The following C program shows how to call a function min() with varying list of arguments. The first argument in the list is the number of arguments in the function call.
//Program to find minimum number in a list of arguments
#include<stdio.h>
#include<stdarg.h>
#include<conio.h>
#include<limits.h>
int min(int cnt,...)
{
va_list valist;
int i,n,min=INT_MAX;
va_start(valist,cnt);
printf("\nArguments in the function call\n");
for(i=0;i<cnt;i++)
{
n=va_arg(valist,int);
printf("%d ",n);
if (n<min)
min=n;
}
va_end(valist);
return min;
}
main()
{
clrscr();
printf("\nThe smallest number in the list is %d\n",min(6,90,35,2,68,108,18));
printf("\nThe smallest number in the list is %d\n",min(10,6,5,7,-5,100,30,25,0,1,10));
getch();
}
/*
OUTPUT
-------
Arguments in the function call
90 35 2 68 108 18
The smallest number in the list is 2
Arguments in the function call
6 5 7 -5 100 30 25 0 1 10
The smallest number in the list is -5
*/
No comments:
Post a Comment