When a line of code ends with the \
(backslash) character, the newline character is deleted. The compiler considers the next line a
continuation of the current line, resulting in only one logical line of code.
This source code transformation, known as line-splicing, occurs during the second phase of C and C++ translation.
Line-splicing is often harmless and is sometimes used to improve the readability of macros:
#define LOG_FAILURE(CONDITION, MESSAGE) \
do { \
if (!(CONDITION)) { \
log(MESSAGE); \
} \
} while (0)
Furthermore, line-splicing does not apply inside C++11 raw string literal.
However, the effect of line-splicing in single-line comments (//
) can be surprising, leading to unintentional code removal
and possibly undefined behavior.
In the following example, the return
expression is considered part of the previous comment. The function has undefined behavior
because it exits without returning a value.
bool isSpecialCharacter(char c)
{
// Noncompliant comment: it ends with a backslash.
// Characters considered special: [ ] \
return 91 <= c && c <= 93;
}
Compilers may also delete whitespace characters between a backslash and the newline characters. This practice is standard-compliant since C++23. In
other words, trailing whitespaces do not disable line-splicing.