Reputation: 335
1st - What's the difference between
#define s 0xFF
and
#define s '\xFF'
2nd - Why the second line equals to -1? 3rd - Why after I try this (in the case of '\xFF')
unsigned char t = s;
putchar(t);
unsigned int p = s;
printf("\n%d\n", p);
the output is
(blank)
-1
?
thanks:)
Upvotes: 6
Views: 28386
Reputation: 30489
You can use '\xFF'
in a string literal as last character and also as middle character using string concatenation but same is not true for 0xFF
.
Difference between '\xFF'
and 0xFF
is analogous to difference between 'a'
and code of character 'a'
(Let's assume it is 0x61
for some implementation) with only difference '\xFF'
will consume further hex characters if used in string.
When you print the character FF
using putchar, output is implementation dependent. But when you print it as an integer, due to default promotion rule of varargs, it may print -1
or 255
on systems where char
behaves as signed char
and unsigned char
respectively.
Upvotes: 2
Reputation: 311068
This
#define s 0xFF
is a definition of hexadecimal integer constant. It has type int
and its value is 255 in decimal notation.
This
#define s '\xFF'
is a definition of integer character constant that represented by a hexadecimal escape sequence. It also has type int
but it represents a character. Its value is calculated differently.
According to the C Standard (p.#10 of section 6.4.4.4 Character constants)
...If an integer character constant contains a single character or escape sequence, its value is the one that results when an object with type char whose value is that of the single character or escape sequence is converted to type int.
It seems that by default your compiler considers values of type char as values of type signed char. So according to the quote integer character constant '\xFF' has negative value because the sign bit (MSB) is set and is equal to -1.
If you set the option of the compiler that controls whether type char is considered as signed or unsigned to unsigned char then '\xFF' and 0xFF will have the same value that is 255.
Take into account that hexadecimal escape sequences may be used in string literals along with any other escape sequences.
Upvotes: 9