Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++11 what should happen first: raw string expansion or macros?

This code works in Visual C++ 2013 but not in gcc/clang:

#if 0 R"foo( #else int dostuff () { return 23; } // )foo"; #endif dostuff(); 

Visual C++ removes the if 0 first. Clang expands the R raw string first (and never defining dostuff). Who is right and why?

like image 249
starmole Avatar asked Jun 23 '15 08:06

starmole


People also ask

What is raw string in programming?

A raw string in programming allows all characters in a string literal to remain the same in code and in the material, rather than performing their standard programming functions. Raw strings are denoted with the letter r, or capital R, and might look something like this: R “(hello)”

What does the '#' symbol do in macro expansion?

The number-sign or "stringizing" operator (#) converts macro parameters to string literals without expanding the parameter definition. It's used only with macros that take arguments.

What is a raw string in C?

A rawstring is a string literal (prefixed with an r) in which the normal escaping rules have been suspended so that everything is a literal.

What is Stringify in C++?

“Stringification” means turning a code fragment into a string constant whose contents are the text for the code fragment. For example, stringifying foo (z) results in “foo (z)” . In the C & C++ preprocessor, stringification is an option available when macro arguments are substituted into the macro definition.


1 Answers

[Update: Adrian McCarthy comments below saying MSVC++ 2017 fixes this]

GCC and clang are right, VC++ is wrong.

2.2 Phases of translation [lex.phases]:

[...]

  1. The source file is decomposed into preprocessing tokens (2.5) and sequences of white-space characters (including comments).

  2. Preprocessing directives are executed, [...]

And 2.5 Preprocessing tokens [lex.pptoken] lists string-literals amongst the tokens.

Consequently, parsing is required to tokenise the string literal first, "consuming" the #else and dostuff function definition.

like image 132
Tony Delroy Avatar answered Sep 22 '22 13:09

Tony Delroy