C++ 中的反斜杠是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19405196/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does a backslash in C++ mean?
提问by Christian
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.
我添加了数据类型,因为它们可能是相关的。谢谢你的帮助。
回答by John Dibling
Backslashes denote two different things in C++, depending on the context.
反斜杠在 C++ 中表示两种不同的东西,具体取决于上下文。
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.
在引号字符串之外(见下文),a\
用作行继续符。行尾(不可见)的换行符会被预处理器有效地忽略,并将下一行附加到当前行。
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:
在 C++ 中,空格在大多数情况下都无关紧要,因此在这个特定示例中,不需要继续行。这应该编译得很好:
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:
由于预处理器处理 a#define
直到到达换行符,因此行延续在宏定义中最有用。例如:
#define FOO() \
s23_foo += \
s8_foo * s16_bar;
Without the line continuation character, FOO
would be empty here.
如果没有行继续符,FOO
这里将是空的。
As An Escape Sequence
作为转义序列
Within a quotes string, a backslash is used as a delimiter to begin a 2-character escape sequence. For example:
在引号字符串中,反斜杠用作分隔符以开始 2 个字符的转义序列。例如:
"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:
在这个字符串文字中,\
开始一个转义序列,转义码是n
。 \n
导致在字符串中嵌入换行符。这当然意味着如果您希望字符串包含该\
字符,您也必须对其进行转义:
"hello\there"
results in the string as viewed on the screen:
结果在屏幕上看到的字符串:
hello\there
你好呀
The various escape sequences are documented here.
回答by benjymous
It lets you continue a statement onto the next line - typically you only need it inside a #define macro block
它允许您将语句继续到下一行 - 通常您只需要在 #define 宏块中使用它