Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
chill-cats opened this issue Mar 29, 2020 · 1 comment
Labels

Comments

@chill-cats
Copy link

chill-cats commented Mar 29, 2020

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

@per1234
Copy link
Contributor

per1234 commented Mar 29, 2020

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants