Go Down

Topic: abs() does nothing with longs (Read 905 times) previous topic - next topic

NegatedVoid

Hey,
Not sure if this is a known bug, but running abs() on a long seems to do nothing. It returned a negative number.

The exact code is a little complex, but basically i had:
int blah = abs(struct->somelong - struct->somelong);

and it returned negative

mikalhart

#1
Oct 21, 2008, 08:31 pm Last Edit: Oct 21, 2008, 08:32 pm by mikalhart Reason: 1
Hi NegatedVoid,

This isn't a bug; it's a usage error.  Abs() is indeed returning a positive "long" value, but when you stuff that return into a (short) int variable, you run the risk of overflowing the range of representable int's and getting unexpected results.  It doesn't have anything to do with abs()

void setup ()
{
 Serial.begin(9600);
 long a = 100000;
 long b = 40000;
 int x = a - b;
 Serial.println(x);
}

This function, for example, prints -5536, and not 60000 like you might initially expect.

Mikal

Go Up