12

In the below code, what does the ## do?

 #define MAKE_TYPE(myname) \
 typedef int myname ## Id; \
Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
Venkata
  • 513
  • 1
  • 9
  • 15
  • Essentially a duplicate of [SO 1489932 C Preprocessor and Concatenation](http://stackoverflow.com/questions/1489932/c-preprocessor-and-concatenation/) – Jonathan Leffler Nov 20 '10 at 03:00

2 Answers2

22

The ## in a macro is concatenation. Here, MAKE_TYPE(test) will expand to : typedef int testId.

From 16.3.3 (The ## operator) :

For both object-like and function-like macro invocations, before the replacement list is reexamined for more macro names to replace, each instance of a ## preprocessing token in the replacement list (not from an argument) is deleted and the preceding preprocessing token is concatenated with the following preprocessing token

icecrime
  • 74,451
  • 13
  • 99
  • 111
  • 4
    I would underline the *before the replacement list is reexamined*. If you write `MAKE_TYPE(OBJECT(Foo))` then you will have `typedef int OBJECT(Foo)Id;`... which is obviously invalid. Dealing with macros is... complicated, and best avoided especially for such trivial cases where it only obfuscate things. – Matthieu M. Nov 19 '10 at 15:22
5

icecrime is correct, but something important to point out in the definition is that the tokens need to be valid preprocessing tokens. Examples:

#define CONCAT(a,b) a ## b
CONCAT(ClassyClass, <int>); // bad, <int> is not a valid preprocessing token
CONCAT(Symbol, __LINE__); // valid as both are valid tokens
tyree731
  • 453
  • 3
  • 8
  • 1
    That caused me a great deal of frustration several years ago, as I wanted to concatenate three things together, and the combination of neither the first nor the last pair were valid preprocessing tokens. – David Thornley Nov 19 '10 at 18:04
  • Great point, but not an answer. Should've been a comment to icecrime's. – underscore_d Jul 29 '16 at 15:59