What is a raw string?

S.S. Anne picture S.S. Anne · Jun 21, 2019 · Viewed 20.1k times · Source

I came across this code snippet in C++17 draft n4713:

#define R "x"
const char* s = R"y"; // ill-formed raw string, not "x" "y"

What is a "raw string"? What does it do?

Answer

templatetypedef picture templatetypedef · Jun 21, 2019

Raw string literals are string literals that are designed to make it easier to include nested characters like quotation marks and backslashes that normally have meanings as delimiters and escape sequence starts. They’re useful for, say, encoding text like HTML. For example, contrast

"<a href=\"file\">C:\\Program Files\\</a>"

which is a regular string literal, with

R"(<a href="file">C:\Program Files\</a>)"

which is a raw string literal. Here, the use of parentheses in addition to quotes allows C++ to distinguish a nested quotation mark from the quotation marks delimiting the string itself.