Quantcast
Channel: Arduino Forum - Latest topics
Viewing all articles
Browse latest Browse all 15514

Abs(-32768) behaves differently if argument is an array variable?

$
0
0

I'm having trouble putting this problem into words; I think the code and comments below should illustrate it clearly. The last print statement causes the behavior that I don't understand.

abs(-32768) equates to -32768 (for a signed integer), because +32768 doesn't fit.

So why does IF(abs(-32768) < 0) equate to FALSE, but only if -32768 is stored in an array?

I've tried this on an inventr.io Hero board and on a Sparkfun Redboard Plus, which are both treated as Arduino Unos.

void setup() {
  Serial.begin(9600);
}

void loop() {
  static const signed int NOTARRAY = -32768;
  Serial.println("Value NOT stored in array:");
  Serial.println(NOTARRAY); //This prints -32768
  Serial.println(abs(NOTARRAY)); //This also prints -32768
  Serial.println((NOTARRAY < 0) ? "<0" : ">=0");//This prints "<0"
  Serial.println((abs(NOTARRAY) < 0 ) ? "<0" : ">=0"); //This also prints "<0"

  static const signed int ARRAY[1] = { -32768 };
  Serial.println("Value IS stored in array:");
  Serial.println(ARRAY[0]); //This prints -32768
  Serial.println(abs(ARRAY[0])); //This also prints -32768
  Serial.println((ARRAY[0] < 0) ? "<0" : ">=0"); //This prints "<0"
  Serial.println((abs(ARRAY[0]) < 0 ) ? "<0" : ">=0"); //But THIS prints ">=0", even though ARRAY[0] == abs(ARRAY[0])

  while(true){}
}

13 posts - 4 participants

Read full topic


Viewing all articles
Browse latest Browse all 15514

Trending Articles