rambo
rambo

Reputation: 383

Does a va_list have to be the last argument in a function declaration?

Seemingly simple question, but haven't been able to find an answer on SO or in the C standard. Question is whether a va_list must be the last parameter to a function in C (presuming, of course, the function takes a va_list as a parameter).

For example, is this safe?

int f(int a, char *b, va_list args, char *c);

or does it have to be the following

int f(int a, char *b, char *c, va_list args);

Upvotes: 3

Views: 211

Answers (1)

dbush
dbush

Reputation: 224457

There is nothing special about the va_list type in regard to its use as a parameter to a function, as its inclusion does not make it a variadic function. Both examples are valid.

An actual variadic function must have at least one named argument and ... at the end, and it needs to use va_start and va_end to set a va_list to read the variadic arguments .

Section 7.16p3 of the C standard describes the va_list type:

The type declared is

va_list

which is a complete object type suitable for holding information needed by the macros va_start, va_arg, va_end, and va_copy. If access to the varying arguments is desired, the called function shall declare an object (generally referred to as ap in this subclause) having type va_list. The object ap may be passed as an argument to another function; if that function invokes the va_arg macro with parameter ap, the value of ap in the calling function is indeterminate and shall be passed to the va_end macro prior to any further reference to ap. 253)


  1. It is permitted to create a pointer to a va_list and pass that pointer to another function, in which case the original function may make further use of the original list after the other function returns.

As described here, a va_list or a pointer to a va_list may be passed to a function, and there is no mention of restricting it to the last argument.

Upvotes: 5

Related Questions