arduino / arduino/ArduinoCore-avr

Use of macro functions causes unexpected results when argument has side effect

Open
#324 1 comment 0 reactions 0 assignees View on GitHub
bug
Dominant language
C
Stars
1.5k
Forks
1.1k
PR merge metrics
No merged PRs in 30d

Description

In Arduino.h header file, there are these macro
```cpp
#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
```cpp
#include
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

Contributor guide

No contributing guide indexed for this repository

Research direction

Start in Arduino.h and reproduce the provided sketch using max(rand() % 10, 5). Inspect each listed macro and compare how often arguments with side effects are evaluated. Done means the reported repeated-evaluation behavior is addressed while the existing macro behavior remains covered by appropriate verification.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp
Domain
embedded-iot
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
32/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.