by geenbert » Sat Oct 12, 2013 12:00 am
Your program works correctly, but it doesn't show what you think it shows. That is because the answer is a signed char, but you read it as an unsigned char, and thus you think it's 130.
A signed char however is just 7 bits, and the 8th bit (the leftmost one) is the sign bit. A signed char with value 0b10000010 is not 130, but -126. Signed chars use the two's a complement method for negative numbers, as described on page 439 (you probably haven't reached that part of the course yet).
When you added 10 to 120 you overflowed the signed char by 3, and thus it rolls over 3 to the low end of its range. For a signed char the range is -128 to 127, so the rollover is to -128.
Like this:
127 + 1 = -128
-128 + 1 = -127
-127 + 1 = -126
So an overflow of 3 results in -126, which is what your program showed.
While you are at it: the table on page 111 states that a signed char is in the range of -128..128, that's a typo and should be -128..127.
BTW numbers with no prefix are assumed to be digital, for binary use 0b (and for hex 0x) as prefix, as used throughout the course.