Skip to content

Trivia impact: rare

The Backslash That Stayed a Backslash

an escape sequence that arrives as two ordinary characters

std::cout << R"(line one\nline two)" << '\n';

Does this print one line or two?

Answer
line one\nline two

The final character is the only newline; the apparent escape in the raw literal stayed a backslash followed by an n.

Why

A raw string literal is introduced by R"delimiter( and ends at its matching delimiter. [lex.string] does not process escape sequences inside those delimiters, so \n is not a newline character there. The ordinary character literal after it supplies the one actual newline in the observed output. A raw literal can also choose a custom delimiter when its contents contain )".

Where it shows up

Regular expressions, JSON fragments, Windows paths, and examples containing many backslashes are the practical cases. It is a source-spelling feature: the bytes in the resulting string are still ordinary bytes.

Takeaway: Raw string literals preserve backslashes instead of interpreting escapes.

Try it: g++ -std=c++17 main.cpp -o demo && ./demo

Open in Compiler Explorer ↗ Quiz this entry