ArduinoCore-avr icon indicating copy to clipboard operation
ArduinoCore-avr copied to clipboard

Potential bug in min(), max(), abs(), constrain(), round(), sq() macros when using with function call

Open chill-cats opened this issue 5 years ago • 1 comments

In Arduino.h header file, there are these macro

#define min(a,b) ((a)<(b)?(a):(b))
#define max(a,b) ((a)>(b)?(a):(b))
#define abs(x) ((x)>0?(x):-(x))
#define constrain(amt,low,high) ((amt)<(low)?(low):((amt)>(high)?(high):(amt)))
#define round(x)     ((x)>=0?(long)((x)+0.5):(long)((x)-0.5))
#define sq(x) ((x)*(x))

When using these macros with function calls, the function get called twice (or multiple times), which cause potential bug (when function return different value) Simple test program which show this bug

#include <Arduino.h>
void setup() {
    Serial.begin(9600);
}

void loop() {
    for (int i = 0; i < 20; i++) {
        Serial.println(max(rand() % 10, 5));
    }
    while (true) {
        // stop
    }
}

Reference: https://www.youtube.com/watch?v=j0_u26Vpb4w&t=632s

chill-cats avatar Mar 29 '20 03:03 chill-cats

Note that, as discussed at https://github.com/arduino/ArduinoCore-API/issues/85, this issue has already been resolved for min and max in arduino/ArduinoCore-API:

https://github.com/arduino/ArduinoCore-API/blob/82a5055a0588976c8df8c1ff3d978f62d68410f3/api/Common.h#L124-L149

So it would be partially resolved by migrating this core to using ArduinoCore-API (https://github.com/arduino/ArduinoCore-avr/pull/329)


The Arduino Language Reference does warn about this problem: https://github.com/arduino/reference-en/pull/513

per1234 avatar Mar 29 '20 07:03 per1234