bug in Abs() function ?

Hi there,

Thanks for keeping up the best developing work on the Arduino. I think I found a bug:

unsigned long lastSecondLaserTriggedTime=0;
unsigned long lastFirstLaserTriggedTime=0;
long lowestLaserTriggedTimeInterval=2^20; // initiate it to a very high value
long passedTimeTemp=0; // only used in interrupts


      lastSecondLaserTriggedTime = 100;
      lastFirstLaserTriggedTime = 1000;
      passedTimeTemp = abs(lastSecondLaserTriggedTime - lastFirstLaserTriggedTime);
      Serial.println(passedTimeTemp);

If you'd take the above code it return a negative value! I guess the arguments to ABS (called overloading?) are performing correctly.

To fix I had to do like this:

unsigned long lastSecondLaserTriggedTime=0;
unsigned long lastFirstLaserTriggedTime=0;
long lowestLaserTriggedTimeInterval=2^20; // initiate it to a very high value
long passedTimeTemp=0; // only used in interrupts


      lastSecondLaserTriggedTime = 100;
      lastFirstLaserTriggedTime = 1000;
      passedTimeTemp = lastSecondLaserTriggedTime - lastFirstLaserTriggedTime;
      passedTimeTemp = abs(passedTimeTemp);
      Serial.println(passedTimeTemp);

Is this a known bug ?

When you do math on two unsigned variables you get an unsigned result. The result will never be negative. When you store that result in a signed value it may show as a negative number.

unsigned int a = 16, b = 32;
int c = a-b;

a = 0x0010;
b = 0x0020;
a-b = 0xfff0; // 65520
c = 0xfff0; // -16

Is this a known bug ?

Yes ( not really a bug, but #define side effect ), This thread will explain why you get strange results, turned into a large discussion.

http://arduino.cc/forum/index.php/topic,84364.0.html

I see now. thanks for your replies.