I just spent a couple of hours to find a way to "protect" commas in C/C++ preprocessor parameters. Consider the following example:
#define ID(x) x //...
This will not work. My compiler will say:
c:\test.cpp(7) : warning C4002: too many actual parameters for macro 'ID'
The problem is that the comma between "hello" and "world" is interpreted as argument seperator of the ID macro (which makes the two being two arguments), although we want it to be part of one single argument. There's no way known to me to protect the comma (like protecting quotes with a backslash in C). Still, there's a workaround.
The solution
The trick is to define another macro which takes many parameters and concatenates them putting commas between them. This can be combined with variadic macros to be able to concatenate as many arguments as you want.
#define CONCAT(...) __VA_ARGS__
The ellipsis takes as an arbitrary number of arguments, __VA_ARGS concatenates them using commas as seperators.
Now, the following will work.
#define CONCAT(...) __VA_ARGS__ #define ID(x) x //...
Conclusion
The lengthy search for that solution taught me another time not to use macros if you don't absolutely have to. Unfortunately, in my case, i had to. In case someone else has to as well, he may find that trick useful.
Comments
Or, you could do this...
Notice the extra pair of parentheses.
easy
lol, that was easy.
Thanks! I did need this tip.
Hi Ingo-
Thanks for the writeup - I found it through the C++ forum* and I appreciate your having posted it to there.
-Charlie
*
http://cboard.cprogramming.com/cplusplus-programming/100211-warning-c400...