Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding a C++ Macro that uses #

Tags:

c++

macros

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

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

Couold you please explain me the use of # in here? I wanted to put the macro in a static function but before I would like to fully understand what it does.

Thanks

like image 828
dau_sama Avatar asked Jan 18 '23 00:01

dau_sama


1 Answers

The use of # in a macro means that the macro argument will be wrapped in quotes "":

#define FOOBAR(x) #x

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

output

hello world what's up?

Another example

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

:/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 read more?

Check out the following link to a entry in the cpp (C Pre Processor) documentation:

  • Stringification - The C Preprocessor
like image 77
Filip Roséen - refp Avatar answered Jan 25 '23 03:01

Filip Roséen - refp