Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have a variadic function in C with no non-variadic parameter?

I have the following function:

void doStuff(int unusedParameter, ...)
{
    va_list params;
    va_start(params, unusedParameter);
    /* ... */
    va_end(params);
}

As part of a refactor, I'd like to remove the unused parameter without otherwise changing the implementation of the function. As far as I can tell, it's impossible to use va_start when you don't have a last non-variadic parameter to refer to. Is there any way around this?

Background: It is in fact a C++ program, so I could use some operator-overloading magic as suggested here, but I was hoping not to have to change the interface at this point.

The existing function does its work by requiring that the variable argument list be null-terminated, and scanning for the NULL, therefore it doesn't need a leading argument to tell it how many arguments it has.

In response to comments: I don't have to remove the unused parameter, but I'd do it if there were a clean way to do so. I was hoping there'd be something simple I'd missed.

like image 833
Tim Martin Avatar asked Apr 12 '10 12:04

Tim Martin


People also ask

How do you access variadic arguments?

To access variadic arguments, we must include the <stdarg. h> header.

Is printf variadic function?

The C printf() function is implemented as a variadic function.

How does Varargs work in C?

You call it with a va_list and a type, and it takes value pointed at by the va_list as a value of the given type, then increment the pointer by the size of that pointer. For example, va_arg(argp, int) will return (int) *argp , and increment the pointer, so argp += sizeof int .


1 Answers

In GCC, you have a workaround: You can define a macro with a variable number of arguments and then add the dummy parameter in the expansion:

#define doStuff(...) realDoStuff(0, __VA_ARGS__)
like image 152
Aaron Digulla Avatar answered Oct 14 '22 09:10

Aaron Digulla