Understanding a C ++ Macro Using #

I have a C ++ macro with syntax that I have never seen before:

#define ASSERT(a) \ if (! (a)) \ { \ std::string c; \ c += " test(" #a ")"; } 

Fired, please explain to me the use of # here? I wanted to put the macro in a static function, but before I wanted to fully understand what it was doing.

thanks

+4
source share
3 answers

Using # in a macro means that the macro argument will be enclosed in quotation marks "" :

 #define FOOBAR(x) #x int main (int argc, char *argv[]) { std::cout << FOOBAR(hello world what up?) << std::endl; } 

Output

 hello world what up? 

Another example

In the following, we display the contents of foo.cpp, and then what the file will look like after the pre-processor starts:

 :/tmp% cat foo.cpp #define STR(X) #X STR (hello world); 

...

 :/tmp% g++ -E foo.cpp # only run the preprocessor # 1 "foo.cpp" # 1 "<command-line>" # 1 "foo.cpp" "hello world"; 

Where can I find out more?

Note the following link to the cpp (C Pre Processor) documentation entry:

+7
source

Inside the macro, # "builds" the variable name. By "stringify" I mean that the variable name is converted to a string literal.

For example, if you have the following macro:

#define PRINT_VARIABLE_NAME (var) printf (#var);

And use it like this:

 int i; PRINT_VARIABLE_NAME(i); 

He will print "i".

In your case, the string will be concatenated with the "test".

+2
source

#a is a string containing the literal a . See Stringfication for more details.

0
source

Source: https://habr.com/ru/post/1387347/


All Articles