In this tutorial you will learn about the C Variable Arguments and its application with practical example.
In C Programming Language a function usually takes a fixed number of arguments and their data type is also declared therein function declaration, in this scenario we are aware of the number of c variable arguments required, but there are situations come across where the number of arguments is not fixed or not known beforehand when the function is written. The most well-known example would be printf, which takes one required parameter, and may also optionally be passed one or more additional parameters.
Let’s take look at the below example code –
1 2 3 4 5 6 7 8 9 10 11 12 |
int sum(int, ... ) { . . . } int main() { sum(1, 2, 3); sum(1, 2, 3, 4); } |
In C Programming Language we can define a function with a variable number of arguments. This can be achieved using three special macros va_start, va_arg & va_end are defined in stdarg. h, to process the variable arguments.
In order to access the c variable argument list, va_start must be called as below –
1 |
void va_start(va_list pvar, void pname); |
va_start() is used to initialize pvar to the beginning of the variable argument list. va_start() must be invoked before any access to the unnamed arguments.
The parameter ‘pname’ is the identifier of the rightmost parameter in the variable parameter list in the function definition (the one just before the ellipses ie., “, …”).
After the initialization, we can access the variable argument list via va_arg macro.
1 |
(type *) va_arg(va_list pvar, type); |
pvar is a pointer to the variable argument list, and type is the type name of the next argument to be returned.
va_arg() expands to an expression that has the type and value of the next argument in the call. The parameter pvar must be initialized by va_start(). Each call to this macro will extract the next argument from the argument list as a value of the specified type.
When all the arguments have been processed, the va_end function should be called. This will prevent the va_list supplied from being used any further. The va_end function is declared as
1 |
void va_end(va_list pvar); |
pvar is a pointer to the variable argument list
The va_end() macro is used to clean up. If va_end is not used, the behavior is undefined. The entire argument list can be re-traversed by calling va_start again, after calling va_end.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include<stdio.h> #include<stdarg.h> void hello(char *msg, ...); int main() { hello("counter",1,5,10,15); return 0; } void hello(char *msg, ...) { va_list ptr; int num; va_start(ptr, msg); num = va_arg(ptr, int); num = va_arg(ptr, int); printf("counter is %d", num); } Output: counter is 5 |