Skip to content

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

Open
@chill-cats

Description

@chill-cats

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

Activity

per1234

per1234 commented on Mar 29, 2020

@per1234
Contributor

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Potential bug in min(), max(), abs(), constrain(), round(), sq() macros when using with function call · Issue #324 · arduino/ArduinoCore-avr