Figure: C functions for summation.
If you ever coded in C programming language, you might be wondering how the standard functions like printf() and scanf() can accept variable number of arguments in the function call. These functions which can accept variable number of arguments is known as **variadic **/ varargs function.
You may come up with a need to code for a variadic function from time to time, so the standard library <stdarg.h> is here to help you in writing your own variadic function.
For example, as shown in the Figure above, if you need a function that can perform summation with n numbers, where n can be any number more than 1, you would not want to write multiple summation functions, instead you need a variadic function in this case.
There are three function-like macros that we need to understand before we can write our own variadic function:
va_start(va_list pargs, last)
This macro accepts two arguments.
This macro initialises the argument pointer variable pargs to point to the first optional argument accepted by the variadic function.
va_arg(va_list pargs, type)
This macro accepts two arguments.
This function returns the value of the argument pointed by pargs, and also update the pargs to point to the next argument in the list.
va_end(va_list pargs)
This macro ends the use of pargs. According to this manual page, after calling va_end(pargs), further va_arg calls with pargs may not work. However, in GNU C library, va_end does nothing, so you may not necessary to use it except for portability reason.
#c-programming #function #c