Arguments Passing in C

The information is passed to the functions by using arguments. Basically, a function consists of fixed number of parameters and for every parameter passing of an argument is needed.

How to pass variable arguments??

Here is an advancement in Arguments Passing in C, where a function can pass variable number of arguments to that particular function.

Passing variable arguments can be considered as minimal version of printf(). The confusion arises here is how printf() will follow the arguments list without specifying any name. Then there comes the use of “stdarg.hÂ header file in which a group of macros are defined to walk through the arguments list. But, there is no chance for determining the data-type of arguments passed.

int function(datatype x, . . .)
{
va_list arguments_list;
va_start(arguments_list, x);
.
loop declaration
{
y=va_arg(arguments_list,datatype);
}
.
.
}
va_end(arguments_list);

1. (…) three dots in the function declaration is ellipses denoting the last arguments in the function.
2. The x before the dots denotes the total number of arguments which is always an integer data type.This is because, the function counts the number of arguments passed.
3. va_list is also called as “argument pointer” ,Â as this will declare the variable that refers to every argument as a reflection in the function.
4. va_start macroÂ initializes the va_list such that it points to the first argument passed.
5. va_argÂ is used to return one argument at a time and then steps to next argument declaring datatype to every argument.
6. va_end is used for cleaning up. Before the program return, ‘va_end’ should be called.

#include<stdio.h>
#include<conio.h>
#include<stdarg.h>
int average(int cnt,...)
{
int sum=0,i;
va_list lst;
va_start(lst,cnt);
for(i=0; i<cnt; i++)
{
int n=va_arg(lst,int);
sum+=n;
}
va_end(lst);
return sum;
}
int main()
{
printf("average of 4,1,2,3,4 = %d\n",average(4,1,2,3,4));
printf("average of 3,1,2,3 = %d\n",average(3,1,2,3));
printf("average of 7,1,2,3,4,5,6,7 = %d\n",average(7,1,2,3,4,5,6,7));
printf("average of 2,1,2 = %d\n",average(2,1,2));
return 0;
}

Output:

average of 4,1,2,3,4 = 10
average of 3,1,2,3 = 6
average of 7,1,2,3,4,5,6,7 = 28
average of 2,1,2 = 3


Summary

“Arguments Passing in C” chapter draws out following important points.

• Variable arguments can be used by including “stdarg.h” header file in the program.
• Variable arguments is replacement of printf() function.

• When function gets multiple arguments which changes at run-time, then the best preference is variable arguments.
• Do not forget to use 3 dots(…) in the function declaration.