BASIC User Group > Code Repository

Number of Arguments in Macros

(1/1)

kryton9:
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

VA_NUM_ARGS(x,y,z)
VA_NUM_ARGS(x,y)
VA_NUM_ARGS(x)
VA_NUM_ARGS()

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

I got this from this cool discussion, many more good macros there.
http://efesx.com/2010/07/17/variadic-macro-to-count-number-of-arguments/#more-1003

kryton9:
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):
max(1,2,3);
--- 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

John:
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.


Navigation

[0] Message Index

Go to full version