1
#include <stdio.h>
#define PRINT(name) print ## name()

void printHE()
{
    printf("Hello");
}
void printWO()
{
    printf("World\n");
}


enum {
    HE,
    WO,
};

int main()
{
    PRINT(HE);
    PRINT(WO);
}

It works perfectly, but why?

What does ## in #define mean?

And why HE didn't convert to 0 ?

Lidong Guo
  • 2,817
  • 2
  • 19
  • 31

4 Answers4

4

Given that you're asking about ## I am assuming that PRINT is defined as

#define PRINT(X) print##X()

The ## is a token-pasting operator, it connects two tokens to its left and to its right together, producing a single token.

When you write PRINT(HE), preprocessor converts that to printHE(), which is a regular function call.

since HE is a enum, should HE translate to 0

That's a very good question! The translation does not happen, because preprocessor runs before enums are interpreted, so the fact that HE and WO are enum members does not change anything.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

It is the escape sequence in your expression. It concatenates the leftmost and the rightmost to produce the token.

## is token pasting operator

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
0

In #define PRINT(name) print ## name

## is token pasting operator, used to "glue" tokens together

P0W
  • 46,614
  • 9
  • 72
  • 119
0

On my computer, it doesn't work right. Print error like below:

two_sharp.c:(.text+0x3a): undefined reference to PRINT' two_sharp.c:(.text+0x46): undefined reference toPRINT' collect2: ld returned 1 exit status

styshoo
  • 111
  • 4