What does a backslash in C++ mean?

Backslashes denote two different things in C++, depending on the context.

As A Line Continuation

Outside of a quotes string (see below), a \ is used as a line continuation character. The newline that follows at the end of the line (not visible) is effectively ignored by the preprocessor and the following line is appended to the current line.

So:

s23_foo += \ 
s8_foo * s16_bar;

Is parsed as:

s23_foo += s8_foo * s16_bar;

Line continuations can be strung together. This:

s23_foo += \ 
s8_foo * \
s16_bar;

Becomes this:

s23_foo += s8_foo * s16_bar;

In C++ whitespace is irrelevant in most contexts, so in this particular example the line continuation is not needed. This should compile just fine:

s23_foo += 
s8_foo * s16_bar;

And in fact can be useful to help paginate the code when you have a long sequence of terms.

Since the preprocessor processed a #define until a newline is reached, line continuations are most useful in macro definitions. For example:

#define FOO() \
s23_foo += \ 
s8_foo * s16_bar; 

Without the line continuation character, FOO would be empty here.

As An Escape Sequence

Within a quotes string, a backslash is used as a delimiter to begin a 2-character escape sequence. For example:

"hello\n"

In this string literal, the \ begins an escape sequence, with the escape code being n. \n results in a newline character being embedded in the string. This of course means if you want a string to include the \ character, you have to escape that as well:

"hello\\there"

results in the string as viewed on the screen:

hello\there

The various escape sequences are documented here.


It lets you continue a statement onto the next line - typically you only need it inside a #define macro block

Tags:

C++

Syntax