Search code examples
cc-preprocessorc99variadic-macrosstringification

Token pasting in C


After reading about VA_NARG

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

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've read this from C-faq. But still could not get it to work...


Solution

  • This is because of the evaluation rules for macros. You would have to define some sort of helper macro that receives 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 could also have a glance into the prerelease of the documentation of P99. This will provide you more comfortable macro tools to do that directly.