Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 877
Nyan Avatar asked Sep 22 '10 12:09

Nyan


People also ask

What is macro in C?

Macros and its types in C/C++ A macro is a piece of code in a program that is replaced by the value of the macro. Macro is defined by #define directive. Whenever a macro name is encountered by the compiler, it replaces the name with the definition of the macro.

What is the use of #define directive?

The #define directive causes the compiler to substitute token-string for each occurrence of identifier in the source file. The identifier is replaced only when it forms a token. That is, identifier is not replaced if it appears in a comment, in a string, or as part of a longer identifier.

What is concatenation of macro parameters?

Concatenation means joining two strings into one. In the context of macro expansion, concatenation refers to joining two lexical units into one longer one. Specifically, an actual argument to the macro can be concatenated with another actual argument or with fixed text to produce a longer name.

Can macro return a value?

Macros just perform textual substitution. They can't return anything - they are not functions.


1 Answers

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.

like image 143
Jens Gustedt Avatar answered Oct 08 '22 15:10

Jens Gustedt