K
Keith Thompson
It's not cast *as* an unsigned char. It's cast (i.e., explicitly
converted) *to* unsigned char. I emphasize the point because I
suspect it may be near the root of your misunderstanding.
Right. The only values that can be stored in an object of type
unsigned char are in the range 0 .. UCHAR_MAX, where UCHAR_MAX is at
least 255 (and typically is exactly 255).
*Converting* the int value -1 to an unsigned type, because of
the way the language defines signed-to-unsigned conversions, is
a handy way of getting the maximum value of the unsigned type.
The conversion changes the mathematical value.
So even without a cast, I can write:
unsigned char uc;
uc = -1;
but the value stored in uc, after conversion, is UCHAR_MAX.
That's UCHAR_MAX + 1 - 42 (typically 214). What about it?
If you have a copy of the standard
(<http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf> is the
latest very-nearly-official draft), take a look at the section on
conversions, particularly between signed and unsigned types.
converted) *to* unsigned char. I emphasize the point because I
suspect it may be near the root of your misunderstanding.
[...](unsigned char)-1 is the largest possible value that can be stored in
an unsigned char.
Ok. But an unsigned char can't *have* the value negative one, right?
Right. The only values that can be stored in an object of type
unsigned char are in the range 0 .. UCHAR_MAX, where UCHAR_MAX is at
least 255 (and typically is exactly 255).
*Converting* the int value -1 to an unsigned type, because of
the way the language defines signed-to-unsigned conversions, is
a handy way of getting the maximum value of the unsigned type.
The conversion changes the mathematical value.
So even without a cast, I can write:
unsigned char uc;
uc = -1;
but the value stored in uc, after conversion, is UCHAR_MAX.
How
about ((unsigned char) -42) ?
That's UCHAR_MAX + 1 - 42 (typically 214). What about it?
If you have a copy of the standard
(<http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf> is the
latest very-nearly-official draft), take a look at the section on
conversions, particularly between signed and unsigned types.