I have two functions foo1(a,b) & foo2(a,b,c) and a macro
#define add(a,b) foo(a,b)
I need to re-define macro to accomplish,
1.if add() is called with 2 parameters, then call foo1
- if add() is called with 3 parameters then call foo2
Im new to the option VA_ARGS. How can I do that
That usual trick for counting arguments may be adapted for this:
Once you plow through the boiler plate, it basically just involves placing all the arguments in a line, with the function tokens after them, and seeing which function stands out. That's what
EXPAND_ADD_SEL_FUNC
does.You can see it live on coliru.
But I'll reiterate what we told you in comments. This is likely to be a sub-par solution to a proper function. I haven't tested it thoroughly, so breakage is easily possible. Use at your own risk.
If you must use variadic macros, then here is a trick.
_Generic
check which type you got, then call the proper function based on that.This is 100% standard C and also type safe.
Demo:
If you just want to distinguish between two functions, the following works:
The auxiliary macro
ADD
always picks the fourth argument:The drawback is that you get quite cryptic error messages when you don't supply two or three arguments to the function.
The advantage over variadic functions is that you get type safety. For example if your functions operate on
double
s, you can still sayadd(1, 2)
and the integer arguments will be converted todouble
s. And variadic functions require some additional information on the number of actual arguments, so that's not a feasible solution here, unless you specify the number of summands in the function.Addendum: I've changed the
add
macro so that it doesn't pass an empty variadic list toADD
. Some compilers allow empty lists, but it isn't standard C.