How to properly add hex escapes into a string-literal?

后端 未结 3 822
轻奢々
轻奢々 2020-11-28 11:26

When you have string in C, you can add direct hex code inside.

char str[] = \"abcde\"; // \'a\', \'b\', \'c\', \'d\', \'e\', 0x00
char str2[] = \"abc\\x12\\x         


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 12:04

    Use 3 octal digits:

    char problem[] = "abc\022e";
    

    or split your string:

    char problem[] = "abc\x12" "e";
    

    Why these work:

    • Unlike hex escapes, standard defines 3 digits as maximum amount for octal escape.

      6.4.4.4 Character constants

      ...

      octal-escape-sequence:
          \ octal-digit
          \ octal-digit octal-digit
          \ octal-digit octal-digit octal-digit
      

      ...

      hexadecimal-escape-sequence:
          \x hexadecimal-digit
          hexadecimal-escape-sequence hexadecimal-digit
      
    • String literal concatenation is defined as a later translation phase than literal escape character conversion.

      5.1.1.2 Translation 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. 8)

      2. Adjacent string literal tokens are concatenated.

提交回复
热议问题