Variable arguments in C
In C language, its possible to write functions with variable arguments. A function that takes variable number of arguments is also called as variadic function. Below is an example prototype for a variadic function.
int func_name(int num, ...);
func_name - name of the function
num - number of arguments in argument list
...(ellipsis) - used to denote variable arguments
Below are the list of macros availabe in 'stdarg.h' used to retrieve variable arguments.
void va_start (va_list arg, last_arg)
It initializes argument pointer arg to point to first optional argument and last_arg is the last named argument to a function.
type va_arg (va list arg, type)
Returns subsequent optional argument and type is data type of the actual argument
void va_end (va list arg)
Ends the use of variable arguments.
Example C program on variable length argument list
int func_name(int num, ...);
func_name - name of the function
num - number of arguments in argument list
...(ellipsis) - used to denote variable arguments
Below are the list of macros availabe in 'stdarg.h' used to retrieve variable arguments.
void va_start (va_list arg, last_arg)
It initializes argument pointer arg to point to first optional argument and last_arg is the last named argument to a function.
type va_arg (va list arg, type)
Returns subsequent optional argument and type is data type of the actual argument
void va_end (va list arg)
Ends the use of variable arguments.
Example C program on variable length argument list
#include <stdio.h>
#include <stdarg.h>
int sum(int, ...); // function prototype
int sum(int num, ...) {
int i, val, total = 0;
va_list arg;
/* initializes arg pointer to point to 1st optional arg */
va_start(arg, num); // num - no of arguments in parameter list
for (i = 0; i < 5; i++) {
val = va_arg(arg, int); // get subsequent argument
printf("Argument %d: %d\n", i + 1, val);
total = total + val;
}
va_end(arg); // end the use of variable argument
return (total);
}
int main() {
int res;
/* first argument to sum denotes the no of arguments in parameter list */
res = sum(5, 10, 20, 30, 40, 50);
printf("Resultant sum value is %d\n", res);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Argument 1: 10
Argument 2: 20
Argument 3: 30
Argument 4: 40
Argument 5: 50
Resultant sum value is 150
Argument 1: 10
Argument 2: 20
Argument 3: 30
Argument 4: 40
Argument 5: 50
Resultant sum value is 150
Variable arguments in C
Reviewed by Mursal Zheker
on
Selasa, Desember 31, 2013
Rating:
Tidak ada komentar: