When using escape sequences in a string or character literal, the rules that determine the end of the sequence are complex:
- A hexadecimal sequence (
\x45
) ends on the first character that is not a hexadecimal digit.
- An octal sequence (
\123
) ends on a character that is not an octal digit or after 3 digits.
There is potential for confusion if an octal or hexadecimal escape sequence is immediately followed by other characters. Instead, such sequences
shall be terminated by either:
- The start of another escape sequence, or
- The end of the character constant or the end of a string literal, or
- Any character that obviously cannot be part of the sequence, like a space, a
[
, any punctuation…
const char *s1 = "\x41g"; // Noncompliant
const char *s2 = "\x41" "g"; // Compliant - terminated by end of literal
const char *s3 = "\x41\x67"; // Compliant - terminated by another escape
const char *s4 = "\x41 g"; // Compliant - terminated by a space
int c1 = '\141t'; // Noncompliant
int c2 = '\141\t'; // Compliant - terminated by another escape
Note that, since C++23, a syntax with delimiters allows writing escape sequences without confusion and should be preferred; see
S7040.