Search code examples
c++stringhexstring-literals

Specifying hex-escaped character followed by a literal hex digit


The following program...

int main () {
    const char str1[] = "\x1bK"; // intent: \x1b followed by 'K'
    const char str2[] = "\x1bE"; // intent: \x1b followed by 'E'
    const char str3[] = "\x1b0"; // intent: \x1b followed by '0'
}

...generates the following compiler warnings for str2 and str3 in all compilers I checked:

warning: hex escape sequence out of range

My intent is to declare three two-character long strings:

  • str1: \x1b + K
  • str2: \x1b + E
  • str3: \x1b + 0

But instead its parsing the last two as if 1be and 1b0 were the specified hex codes.

This seems to happen any time \x?? is followed by a third perceived hexadecimal digit.

In a string literal, how can I specify a character with \x, followed by another character, if that character is also a hexadecimal digit?

I feel like this is a really silly question, but somehow I've never been in this situation before.


Solution

  • You could simply have the compiler concatenate 2 separate string literals.

    int main () {
        const char str1[] = "\x1b" "K";
        const char str2[] = "\x1b" "E";
        const char str3[] = "\x1b" "0";
    }