Is "identical" \ "according to the C / C ++ standard?

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

Code can be compiled using VS 2015.

I'm just curious:

Are both methods compatible with C and / or the C ++ standard?

+5
source share
4 answers

From C++11 ISO Standard

Β§ 2.14.5 String literals [lex.string]

...

15 Episodes and universal symbol names in uneven string literals have the same meaning as in symbolic literals (2.14.3), except that a single quote is represented either by itself or by an escape sequence \

+6
source

Yes, inside the string literal both values ​​are the same.

A character literal requires an escaped version:

 char x = '\''; 

Standard links are two sources. First, the stages of translation. From C.11 and sect 5.1.1.2 (C ++. 11 [ lex.phases ] has a similar language):

  1. Each character set element and escape sequence in character constants and string literals is converted to the corresponding execution character set element ; if there is no corresponding element, it is converted to an element defined in the implementation that is different from the zero (wide) character.

The following is a grammar definition for a character constant and for string literals that allow escape sequences to be used. And a simple escape sequence is an escape sequence in a grammar. C.11 and section 6.4.4.4 defines it (C ++. 11 [ lex.ccon ] has the same definition):

simple escape sequence: one of

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

Finally, for string literals, the standard indicates that the interpretation of the characters in the literal is the same as each of them being a character constant, and then makes an exception. ' From C.11 and sect 6.4.5 (C ++. 11 [ lex.string ] has a similar language):

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

+4
source

\' is a valid escape character sequence in C and C ++. Therefore lines

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

Create equivalent string literals in both C and C ++.

+2
source

Yes, they are identical.

From the C ++ Standard, $ 2.13.3 / 7 Character Literals [lex.ccon]

Table 6 - Time 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 
+2
source

Source: https://habr.com/ru/post/1247583/


All Articles