arduino/ArduinoCore-avr

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

chill-cats opened this issue · 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

Note that, as discussed at arduino/ArduinoCore-API#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 (#329)


The Arduino Language Reference does warn about this problem: arduino/reference-en#513