(ANSI) C Reference: Using stdarg.h for Variable Arguments Handling

There are cases where a function needs to accept varying numbers of arguments of varying type. For this we can use the macros defined in the header file stdarg.h. In this header file (stdarg.h) there macros defined that can be used to access the arguments of a list of unnamed (arguments with no corresponding parameter declarations) arguments.

There is one type described in stdarg.h:

  • va_list Holds the information about variable arguments.
  • The typedef va_list is used by the macros.

The following macros are defined:

  • va_start() Initializes the list of variable arguments.
  • va_arg() Expands the next argument in the parameter list of the function with a type.

    Note: the used va_list must be initialized with va_start.

  • va_end() Allows a function with variable arguments (which used the va_start macro) to return.

    Note: the used va_list may no longer be used after a va_end call.

To use a varying number of arguments (unamed) in a function we have to add a comma and three dots after its regular named parameters:

Usage: return_type function_name( regular_declarations, …)

Example: void my_print(int my_args, …)

Take a look at a source code example:


#include<stdio.h>
#include<stdarg.h>

void printargument(int num_args, ...)
{
	va_list arg_list;
	int my_arg;

	va_start(arg_list, num_args);

	//Print until zero
	for (my_arg = num_args; my_arg != 0; my_arg = va_arg(arg_list, int))
		printf("%d\n", my_arg);

	va_end(arg_list);
}

int main(void)
{
	printargument(5,10,15,0);
	return 0;
}

Note: the for – loop stops if it encounters zero.

Some C compilers also include a va_copy() macro in stdarg.h. This macro can be used to duplicate a va_list object.

This entry was posted in C Reference stdarg.h Functions. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed. Tweet This! Tweet This! or use to share this post with others.

Comments are closed.