11

In a string literal, how can I follow a hexadecimal escape sequence immediately with a literal character that can be interpreted as a hexadecimal digit? For example, if I write this literal ...

"BlahBlah\x04BlahBlah"

... the 'B' immediately following the '4' will be interpreted as part of the hexadecimal escape, because it is a valid hexadecimal digit.

How can I write a string literal that represents the string that the above would represent if the '4' were taken as the last character of the hex escape?

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
wahab
  • 797
  • 2
  • 6
  • 24
  • Please show your research effort till time. Please read [Ask] page first. – Sourav Ghosh Feb 03 '16 at 15:05
  • 4
    You probably want to use the litteral `"BlahBlah\x04" "BlahBlah"`. The compiler sees this as a single string but the escape sequence stops at `4`. – SirDarius Feb 03 '16 at 15:14
  • 1
    "*C treats all characters following a '\x' in a string as hexadecimal numbers*" when using which function, operator, whatever? As it stands it's a "string"-literal and treated as such, and not as a hex-value at all. – alk Feb 03 '16 at 15:14
  • 2
    @alk He's obviously referring to a hex escape sequence inside a string literal, which you can see if you read the code in the question. – Lundin Feb 03 '16 at 15:21

1 Answers1

12

As you noticed, C is pretty dumb when it comes to hex escape sequences in string literals. Fix it by using string concatenation, like this:

"BlahBlah\x04" "BlahBlah"

It is good practice to never have any trailing characters behind such a hex escape sequence. Always end the string as in this example.

Lundin
  • 195,001
  • 40
  • 254
  • 396
  • 2
    Upvoted, but I wouldn't really call it *pre-processor* at that translation phase. – user694733 Feb 03 '16 at 15:25
  • @user694733 Uuh right, that will get mixed up with `##` which I believe is formally named "pre-processor concatenation". I'll edit. – Lundin Feb 03 '16 at 15:33
  • 3
    (For those with a nerdy interest in translation phases, pre-processing is apparently phase 4, hex escape sequences are converted in phase 5, and string literal concatenation is done in phase 6. Which actually explains just why this trick works. See 5.1.1.2 Translation phases. There, I learned something new too!) – Lundin Feb 03 '16 at 15:40