Tuesday, 29 November 2011

Variadic Functions

‎#include<stdarg.h> is a header file which enables us to pass multiple arguments to a function.You can pass multiple arguments by using "..." after d last variable.
for eg: avg(int num,...);
so this function avg(int num,...) vil take variable no of arguments and 1 integer arguments for num.
it has 1 type : va_list to hold info abt variable arguments
and 3 functions
1. va_start
2. va_arg
3. va_end

va_start is used to start iterating by passing it 2 arguments : an object of type va_list
and second parameter is d last named parameter of d function

for eg: avg(int num,...)
den va_list l;
va_start(l,num); //dis initializes d list of variable arguments

now to use individual arguments we use va_arg()
it accepts va_list as first argument and type of d argument in the list.
i.e va_arg(l,int); it returns d arguments in d same order in which dey were passed to the function...!!

when we r done we use va_end to free d memory used by our list.
In c it is mandatory to give 1 normal parameter but in c++ its nt mandatory....!!

No comments:

Post a Comment