Namespaces
Variants
Actions

Escape characters

From cppreference.com


Escapes are a mechanism used to fine-tune how the compiler separates your source program into tokens. As a response to the exercise in Hello World!, you may have created a program similar to the following:

#include <iostream>
 
int main()
{
    std::cout << "Hello";
    std::cout << "World!";
}

Output:

HelloWorld!

Whilst this does indeed output both strings, the output is not two lines. It is pasted together on one single line. If you tried to insert a newline in your source code, this would not have any useful effect. In addition, there is still the problem of how to create output with quotation marks in it. Both of these issues are addressed by escapes.

An escape consists of a backslash \, followed by another character. When this character is a quotation mark, instead of interpreting that as the end of a string token, the compiler keeps the quote as part of the string and continues. When this character is certain other characters, the compiler inserts other special characters into the string. \n is the escape for a newline character.

#include <iostream>
 
int main()
{
    std::cout << "Hello\n\"World\"!";
}

Output:

Hello
"World"!

As you can see, one of the core problems with escapes is that when you start using more than a couple in a row, it can become difficult to read. This becomes even more problematic when using strings that are going to be interpreted by another system afterwards, so the escapes need escaping, and if you want a string that ends in a backslash then you need to escape the backslash so that the backslash doesn't escape the ending quote, and, well, it can become a real mess.

#include <iostream>
 
int main()
{
    std::cout << "\\\n\\\\t\\\\"\\\"\\";
}

Output:

Good luck figuring this out.

C++11 introduced raw string literals which can handle this better. But currently, there is no need to go into further detail about escapes.