Trap in arithmetic

Hi,
I found an error in a simple computation which might be a trap for many beginners in programming. I am not really a beginner, but I fell into this trap, which took me a lot of time to find out.

case 1:
#include <SoftwareSerial.h>

uint32_t thresh = 800;
int32_t tmic_d0, tmic_filt;
SoftwareSerial mySerial(6, 5);  // RX, TX (DO=TX)

setup() {
 mySerial.begin(38400);
  delay(500);

  tmic_d0=15868;
  tmic_filt=15533;
  mySerial.print(tmic_filt);  mySerial.print(" - ");
  mySerial.print(tmic_d0);  mySerial.print(" = "); 
  mySerial.print(tmic_filt-tmic_d0);

  if (tmic_filt -tmic_d0 < thresh) mySerial.print(" < ");
  else mySerial.print(" >= ");
 mySerial.println(thresh);

while(1);
}
case 2:
  same code as in case1 with 1 line changed:
  int32_t thresh = 800;

Serial Monitor shows in case1:

15533 - 15868 = -335 >= 800

which is wrong!

But in case 2 it is ok:

15533 - 15868 = -335 < 800

Comparisons between signed and unsigned variables are handled by the compiler as if both variables were unsigned!
(-335 interpreted as unsigned is more than 4 billion)

This happened to me with an ATtiny84. But I guess it is the same with any other controller.

The compiler can catch many of these common bugs: go to the preferences in the IDE and enable all compiler warnings. It'll warn about the comparison of signed and unsigned integers for case 1.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.