Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi-line raw string literals as preprocessor macros arguments

Tags:

c++

c++11

Can a multi-line raw string literal be an argument of a preprocessor macro?

#define IDENTITY(x) x

int main()
{
    IDENTITY(R"(
    )");
}

This code doesn't compile in both g++4.7.2 and VC++11 (Nov.CTP).
Is it a compiler (lexer) bug?

like image 465
Abyx Avatar asked Nov 30 '12 17:11

Abyx


1 Answers

Multiple line macro invocations are legal - since you are using a raw string literal it should have compiled

There is a known GCC bug for this:

http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52852

If you had been using regular (nonraw) strings it would have been illegal.

This should have compiled:

printf(R"HELLO
    WORLD\n");

But not this:

printf("HELLO
    WORLD\n");

This should be coded as

printf("HELLO\nWORLD\n"); 

if a new line is intended between HELLO and WORLD or as

printf("HELLO "
    "WORLD\n");

If no intervening new line was intended.

Do you want a new line in your literal? If so then couldn't you use

  IDENTITY("(\n)");

The C compiler documentation at

http://gcc.gnu.org/onlinedocs/cpp.pdf

States that in section 3.3 (Macro Arguments) that

"The invocation of the macro need not be 
restricted to a single logical line—it can cross 
as many lines in the source file as you wish."
like image 136
A B Avatar answered Oct 14 '22 16:10

A B