abs() behaviour difference between Nano and Nano Every

And here's another behaviour difference I found between the Nano and the Nano Every.

(All of this is because I'm porting some code from a Nano to a Nano Every and am stumbling across these things; I'm not systematically trying every possible instruction on both boards looking for differences! :wink: )

The abs() macro for the Nano Every doesn't seem to take floats. It worked fine with floats on the Nano.

The following code says "True" on a Nano, but "False" on a Nano Every.

void setup() {
    Serial.begin(115200);
    Serial.println(abs(1.5) > 1 ? "True" : "False");
}

void loop() {
}

On the Every, abs() appears to truncate its argument. Serial.println(abs(-1.9)) on a Nano prints "1.9" but on an Every prints "1".

Another compatibility issue?

In the Arduino AVR Boards core library used by the classic Nano, the implementation of abs() is a macro:

#define abs(x) ((x)>0?(x):-(x))

This macro approach allows it to work with any type.

There is no such macro in the Arduino megaAVR Boards core library used by the Nano Every, so the stdlib abs() is used:
http://www.cplusplus.com/reference/cstdlib/abs/

I believe the reason for the change was the problems caused by the macro approach. For example:

  byte x = 42;
  Serial.print(abs(++x));

prints 44.

You can see some complaints about this here:

They likely plan to eventually make this change to the Arduino AVR Boards core as well when they move it to using ArduinoCoreAPI.

pert:
In the Arduino AVR Boards core library used by the classic Nano, the implementation of abs() is a macro:
ArduinoCore-avr/Arduino.h at 1.8.2 · arduino/ArduinoCore-avr · GitHub

#define abs(x) ((x)>0?(x):-(x))

This macro approach allows it to work with any type.

There is no such macro in the Arduino megaAVR Boards core library used by the Nano Every, so the stdlib abs() is used:
abs - C++ Reference

I believe the reason for the change was the problems caused by the macro approach. For example:

  byte x = 42;

Serial.print(abs(++x));



prints 44.

You can see some complaints about this here:
https://github.com/arduino/ArduinoCore-API/issues?q=abs

Ah ok makes sense, thanks for that. Still a bit of a compatibility issue for already existing code that's being moved from Nano to Nano Every. And one which can take a while to trace!

pert:
They likely plan to eventually make this change to the Arduino AVR Boards core as well when they move it to using ArduinoCoreAPI.

So then code which used to work on a Nano will break? Great... :slight_smile: