Token in C

After reading VA_NARG

I tried to implement function overloading depending on the number of arguments in C using macros. Now the problem is this:

void hello1(char *s) { ... } void hello2(char *s, char *t) { ... } // PP_NARG(...) macro returns number of arguments :ref to link above // does not work #define hello(...) hello ## PP_NARG(__VA_ARGS__) int main(void) { hello("hi"); // call hello1("hi"); hello("foo","bar"); // call hello2("foo","bar"); return 0; } 

I read this from C-faq. But still failed to get it to work ...

+6
c c-preprocessor c99 stringification variadic-macros
source share
3 answers

This is because of evaluation rules for macros. You will need to define some kind of helper macro that gets the number as a token:

 #define HELLO_1(N, ...) hello ## N #define HELLO_0(N, ...) HELLO_1(N, __VARGS__) #define HELLO(...) HELLO_0(PP_NARG(__VA_ARGS__), __VARGS__) 

or so. You can also take a look at the P99 preliminary documentation. This will provide you with more convenient macro tools to do this directly.

+4
source share

This PP_NARG is a pretty impressive piece of insanity!

Following the glue example in the C99 standard (6.10.3.5, example 4), the following gives the desired results:

 #define glue(a, b) a ## b #define xglue(a, b) glue(a, b) #define hello(...) xglue(hello, PP_NARG(__VA_ARGS__))(__VA_ARGS__) 
+4
source share

I do not have a C99 compiler available for verification, but this should work:

 #define helloN(N, ...) hello ## N (__VA_ARGS__) #define hello(...) helloN(PP_NARG(__VA_ARGS__), __VA_ARGS__) 
0
source share

All Articles