Image for post

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.


Understanding the Macro Functions Defined in <stdarg.h>

There are three function-like macros that we need to understand before we can write our own variadic function:

  1. va_start(va_list pargs, last)

  2. This macro accepts two arguments.

    • The first argument is a variable declared as va_list type, which is an argument pointer variable.
    • The second argument is the last fixed argument accepted by the variadic function.
  3. This macro initialises the argument pointer variable pargs to point to the first optional argument accepted by the variadic function.

  4. va_arg(va_list pargs, type)

  5. This macro accepts two arguments.

    • This first argument is same as the first argument in va_start() macro.
    • The second argument specified the expected data type pointed by pargs.
  6. 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.

  7. va_end(va_list pargs)

  8. 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

Variadic Function in C Programming
3.55 GEEK