根据 C/C++ 标准,“'”是否与“\'”相同?

Is "'" identical to "\'" as per the C/C++ standard?

int main()
{
    char* str1 = "Tom's cat";
    char* str2 = "Tom\'s cat";
}

代码可以用VS 2015编译。

我只是想知道:

这两种方式是否都符合Cand/or C++标准?

是的,在一个字符串文字中,两者是相同的。

字符文字需要转义版本:

char x = '\'';

标准参考文献有两个来源。第一,翻译阶段。来自 C.11 §5.1.1.2(C++.11 [lex.phases] 有类似的语言):

  1. Each source character set member and escape sequence in character constants and string literals is converted to the corresponding member of the execution character set; if there is no corresponding member, it is converted to an implementation defined member other than the null (wide) character.

接下来是字符常量和字符串文字的语法定义,它们允许转义序列。而simple-escape-sequence是语法中的转义序列。 C.11 §6.4.4.4 定义它(C++.11 [lex.ccon] 有相同的定义):

simple-escape-sequence: one of

\' \" \? \
\a \b \f \n \r \t \v

最后,对于字符串字面量,标准规定字面量中字符的解释是一样的,就好像每个字符都是一个字符常量,然后例外'。来自 C.11 §6.4.5(C++.11 [lex.string] 有类似的语言):

The same considerations apply to each element of the sequence in a string literal as if it were in an integer character constant (for a character or UTF−8 string literal) or a wide character constant (for a wide string literal), except that the single-quote ' is representable either by itself or by the escape sequence \', but the double-quote " shall be represented by the escape sequence \".

\' 是 C 和 C++ 中的有效字符转义序列。因此,行

char* str1 = "Tom's cat";
char* str2 = "Tom\'s cat";

在 C 和 C++ 中生成等效的字符串文字。

是的,它们是相同的。

来自 c++ 标准,$2.13.3/7 字符文字 [lex.ccon]

Table 6 — Escape sequences

new-line         NL(LF) \n
horizontal tab   HT     \t
vertical tab     VT     \v
backspace        BS     \b
carriage return  CR     \r
form feed        FF     \f
alert            BEL    \a
backslash        \      \
question mark    ?      \?
single quote     ’      \’
double quote     "      \"
octal number     ooo    \ooo
hex number       hhh    \xhhh

来自C++11 ISO Standard

§ 2.14.5 String Literals [lex.string]

...

15 Escape sequences and universal-character-names in non-raw string literals have the same meaning as in character literals (2.14.3), except that the single quote ’ is representable either by itself or by the escape sequence \’