Pikacz
Pikacz

Reputation: 439

C string and hex characters

Can anyone explain what is happening in this code?

    #include <stdio.h>

    void f(const char * str) {
      printf("%d\n", str[4]);
    }

    int main() {
      f("\x03""www""\x01""a""\x02""pl");
      f("\x03www\x01a\x02pl");
      return 0;
    }

why output is?

    1
    26

Upvotes: 5

Views: 13554

Answers (2)

Jim Lewis
Jim Lewis

Reputation: 45085

The issue is with "\x01""a" versus "\x01a", and the fact that the hex->char conversion and the string concatenation occur during different phases of lexical processing.

In the first case, the hexadecimal character is scanned and converted prior to concatenating the strings, so the first character is seen as \x01. Then the "a" is concatenated, but the hex->char conversion has already been performed, and it's not re-scanned after the concatenation, so you get two letters \x01 and a.

In the second case, the scanner sees \x01a as a single character, with ASCII code 26.

Upvotes: 6

Lee Daniel Crocker
Lee Daniel Crocker

Reputation: 13181

In C, characters specified in hex (like "\x01") can have more than two digits. In the first case, "\x01""a" is character 1, followed by 'a'. In the second case, "\x01a", that's character 0x1a, which is 26.

Upvotes: 3

Related Questions