Frage

i know that \x is hexadecimal representation of ASCII literal

printf("%c",'\x41'); // A
printf("%c",'\X41'); // 1

why?

reference: http://c.comsci.us/etymology/literals.html (see most bottom table)

War es hilfreich?

Lösung 2

I request you compile with -Wall option.

aaa.c: In function ‘main’:
aaa.c:6:14: warning: unknown escape sequence: '\X' [enabled by default]
aaa.c:6:14: warning: multi-character character constant [-Wmultichar]

From the above message X is ignored.

And considering '41', this is multi-character character constant.

As @paddy said, last character in the sinle-quotes used. so character '1' is printed.

set of escape sequences

\a alert (bell) character              \\ backslash
\b backspace                           \? question mark
\f formfeed                            \’ single quote
\n newline                             \" double quote
\r carriage return                     \ooo octal number
\t horizontal tab                      \xhh hexadecimal number
\v vertical tab

Andere Tipps

This is not standard, so results will vary.

Given that \X is not a valid control sequence, your particular compiler is choosing the last character in the single-quotes and using that.

So, if you did: '\X12345' you would probably get 5. There is nothing special about \X. If you take that out of your dodgey character literal, you'll get the same result.

The first line \x41 is correct, and 0x41 is the ASCII value of 'A' ans so 'A' is printed.

The second line is a syntax error, as \X (upper case) is not a valid escape sequence. What happens now is dependent on your compiler, but GCC will take \X4 as invalid and ignore it, leaving the '1' as a literal character to be printed.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top