A function with variable number of arguments is called a variadic function, and also known as _variable argument function _[1]. Due to its flexibility in size of the list of input arguments, it is very useful especially in system programming. Its usual use cases include summing of numbers, concatenating strings, and so on. Typical examples include the printf in C programming language, execl and execlp in Unix, execl and execlp in Windows, and many others. This post introduces how to declare/define and use such functions.

How to declare a variadic function

Declaration of a variadic function is almost same as an “ordinary” function, except that its formal parameter list ends with an ellipsis. Below is an example of the declaration of a variadic function.

int sum (int x, ...);

In C programming language, at least one named formal parameter must appear before the ellipsis parameter. Whereas in C++, variadic function without any named formal parameter is allowed, although no argument passed to such function is accessible in this case [2].

The comma between the last named parameter and the ellipsis is optional [2], i.e. “, …”, in the above declaration can be replaced by “…”.

How to use a variadic function

Possibly the first example everybody would think of when discussing variadic function is the function printf. Next, we take a look at the source code of this function [3].

int __printf ( const char *format, ... )
    va_list arg;
    int done;
    va_start (arg, format);
    done = vfprintf (stdout, format, arg);
    va_end (arg);
    return done;

Clearly, the function printf calls vfprintf to implement all the “magics”. However, as the declaration of printf is enough for demonstrating how to define a variadic function, we are not going to dig deeper into the source code of vfprintf. Below the declaration of vfprintf is given.

int vfprintf ( FILE *s, const CHAR_T *format, va_list ap );

In both printf and vfprintf, three macros and one special data type are used to implement variadic functions. They are va_startva_argva_end and va_list. They are defined in the header file _stdarg.h _(cstdarg for C++). To get a glimpse of its implementation, we take a look at an early version of the header file stdarg.h (see this discussion for details on how to check the source code of the latest stdarg.h).

#c-programming-language #cpp #cplusplus #programming-c #c++

How to declare/define and use functions
1.45 GEEK