Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the compiler seeing with this macro? [closed]

Consider this:

  #define STRINGIFY(A) #A

If I then later write:

 STRINGIFY(hello)

Is the compiler actually seeing this:

 #hello

I think it is that additional hash in front of #A that is confusing me.

like image 497
johnbakers Avatar asked Dec 23 '12 13:12

johnbakers


2 Answers

What the compiler sees is this:

"hello"

The hash is preprocessor-only token.

Single hash stringifies the argument.

#define STRINGIFY(x) #x
STRINGIFY(hello)

gets replaced by

"hello"

Double hash concatenates the tokens:

#define CAT(a, b) a##b
#define _STRINGIFY(x) #x
#define STRINGIFY(x) _STRINGIFY(x)
STRINGIFY(CAT(hello,world))

gets replaced by this:

_STRINGIFY(helloworld)

and then by this:

"helloworld"

EDIT: As Pubby pointed out, the example was wrong, the macro replacement doesn't work that way, but now I corrected it.

like image 129
milleniumbug Avatar answered Dec 26 '22 20:12

milleniumbug


You can test it yourself using the -E (*) flag (with gcc/g++):

test.cpp

#define STRINGIFY(A) #A

int main(int argc, const char *argv[])
{
    STRINGIFY(hello);
    return 0;
}

Output of g++ test.cpp -E

# 1 "test.cpp"
# 1 "<command-line>"
# 1 "test.cpp"


int main(int argc, const char *argv[])
{
    "hello";
    return 0;
}

(*): If you use the -E option, nothing is done except preprocessing. - GCC Options Controlling the Preprocessor

like image 21
Vincenzo Pii Avatar answered Dec 26 '22 19:12

Vincenzo Pii