Pages: [1]   Go Down
Author Topic: abs() does nothing with longs  (Read 762 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Newbie
*
Karma: 0
Posts: 1
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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
Logged

Austin, TX USA
Offline Offline
God Member
*****
Karma: 4
Posts: 997
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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
« Last Edit: October 21, 2008, 01:32:14 pm by mikalhart » Logged

Pages: [1]   Go Up
Jump to: