BASIC User Group > Code Repository

Number of Arguments in Macros


I finally found the answer I have been searching for.
How to get the number of arguments in variadic macros.

--- Quote ---GCC (and Clang) both support a special extension for variadic macros; when placing “##” between a comma and __VA_ARGS__ then the comma is only part of the expansion if __VA_ARGS__ does not expand to “nothing”. If it does expand to nothing, the comma is removed.

This extension allows you to easily change the macros to also report zero arguments correctly. Try the following in GCC or Clang:

#define VA_NUM_ARGS(...) VA_NUM_ARGS_IMPL(0, ## __VA_ARGS__, 5,4,3,2,1,0)
#define VA_NUM_ARGS_IMPL(_0,_1,_2,_3,_4,_5,N,...) N


It will print: 3, 2, 1, 0
--- End quote ---

I got this from this cool discussion, many more good macros there.

This is also on that site, but I wanted to post it here in case that site goes down.

--- Quote ---#define max(...) macro_dispatcher(max, __VA_ARGS__)(__VA_ARGS__)

#define max1(a) a
#define max2(a,b) ((a)>(b)?(a):(b))
#define max3(a,b,c) max2(max2(a,b),c)
// ...

// to verify, run the preprocessor alone (g++ -E):
--- End quote ---

Credit see the first post's url.

Both of these worked on Windows mingw using the command shell, I used gcc to test it in c and not g++:  gcc -E  filename.c

Good info Kent. Thanks for the research and posting the mystery of macros revealed.

I have made a T-Shirt for you to wear while creating C BASIC macros.

BTW: The members only code repository board would be a way to get files passed around us that isn't ready for public consumption. Charles seems to be forum friendly and shares here. It would be great if he could join us on C9. I'm sure there is going to come a time with the Cint BASIC version having issues. CINT is only working there at this point. I plan to set up a public workspace once I get a little farther down the road with it. I'm still in discovery mode with the CERN ROOT/CINT package. Seem pretty powerful for what it does.


[0] Message Index

Go to full version