Confusion about type conversions

Hi, I am a newbie learning type conversion for C++. The whole unsigned type conversion is puzzling me. Could someone explain the following examples?

1. unsigned char c = -1; //assuming 8-bit chars

The ex says c has value 255. I checked out the ASCII table, but still can't figure it out. Why is the value 255?

2. signed char c2 = 256; //assuming 8-bit chars

The ex the value of c2 is undefined. Is it because there is no decimal value of 256 defined on the ASCII table?

3. unsigned u = 1; //assuming 32-bit ints
u--;

The ex says when u is 0, it is 4294967259. Explanation, please?
The ASCII table has nothing to do with it. char/signed char/unsigned char are just behaving like ordinary integer types.

Unsigned values wrap around so if you try to go below the smallest value it will instead go to the largest possible value and start going from there. The largest possible value that can be stored in an 8-bit unsigned value is 255. That is why you get 255 when you assign -1 to the unsigned char.

The values in your third example seems to be incorrect. If u is 0 when you do u-- the value of u will become 4294967295 because that is the largest possible value that u can have.

Signed values does not have this "wrap around" behaviour. The C++ standard simply says it's undefined what will happen if you go below or above the allowed range which is -128 ‒ 127 for signed 8-bit (using two's complement representation).
Thank you for the explanations, Peter87.

And you are right, the value of u-- in the second ex is indeed 4294967295.
Topic archived. No new replies allowed.