Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
600 views
in Technique[技术] by (71.8m points)

syntax - What does a backslash in C++ mean?

What does this code: (especially, what does a backslash '' ? )

s23_foo +=  
s8_foo * s16_bar;

I added the datatypes, because they might be relevant. Thanks for your help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
"

In this string literal, the begins an escape sequence, with the escape code being 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:

hellohere

The various escape sequences are documented here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...