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

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.

Leave a Comment