View Single Post
  #6   Spotlight this post!  
Unread 02-02-2008, 18:57
David Fort David Fort is offline
Registered User
FRC #1001
Team Role: Mentor
 
Join Date: Feb 2006
Rookie Year: 2003
Location: Cleveland, OH
Posts: 26
David Fort is on a distinguished road
Re: Problem with negitive numbers

When people say, "overflow", they mean the number goes from its lowest value it can represent to its highest value (or vice versa).

For example, and unsigned char can represent values from 0 to 255.

If you add 1 to 255, you get 0.
If you subtract 1 from 0, you get 255.

Suppose in this expression:
currentOutput[motor] + 127
currentOutput is declared something like this:
unsigned char currentOutput[2];

Then if the value is more than 127, you are going to have trouble. I presume that isn't your case, but I used that example because there is something more interesting:

when you add two things and assign to a larger thing, the promotion to the larger thing doesn't happen until the assignment.

suppose the example above, plus
int x;
x=currentOutput[motor] + 127;

now, since x is an int, you wouldn't (might not) expect the expression currentOutput[motor] + 127 to overflow just because currentOutput[motor] is, say 200, because 200 + 127 is just 327, and that will easily fit in an int.
However, C, first it will add currentOutput[motor] + 127
using byte sized math, and THEN "widen" it to 16 bits to promote it to an integer type. By then, the overflow has occured, you wrapped back around positive infinity to zero, and you have the wrong value.

(small caveat: If the compiler thinks of 127 as an "int" instead of as a "unsigned char" in the example above, then it will first promote both operands of the + to ints. I don't remember the rules for integer literals off hand, and this compiler may well bend them to save some space anyway. To make the example more precise, and applicable to any C compiler (including ANSI compliant ones), then I could have used two unsigned chars, like intX = ucY + ucZ; In this case, the addition of ucY + ucZ might overflow a byte).

I apologize if I went overboard on the detail. This is the sort of thing that confuzles the kids on our team frequently, so I thought maybe some background would help.

David Fort
Team 1001
Hacksaw