C Variable Arguments

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 –

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 –

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.

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

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.



In this tutorial we have learn about the C Variable Arguments and its application with practical example. I hope you will like this tutorial.