Variable Arguments: stdarg.h

Earlier, this chapter discusses variadic macros, macros that can accept a variable number of arguments. The stdarg.h header file provides a similar ability for functions. But the usage is a bit more involved. You have to do the following:

1.
Provide a function prototype using ellipses.
2.
Create a va_list type variable in the function definition.
3.
Use a macro to initialize the variable to an argument list.
4.
Use a macro to access the argument list.
5.
Use a macro to clean up.

Let's look at those steps in more detail. The prototype for such a function should have a parameter list with at least one parameter followed by ellipses:

 void f1(int n, ...); // valid int f2(int n, const char * s, ...); // valid char ...

Get C Primer Plus, Fourth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.