The millis() function returns an unsigned long integer. Implicitly casting it to a signed long is a terrible idea, for several reasons:
- After roughly 24.9 days, the most significant bit of
millis() is set, meaning the cast will result in a negative number, and all the if(time < 0) tests will evaluate to true.
last_run + interval can overflow, and overflowing a signed number in C++ yields undefined behavior, which is always a bug.
- In the lucky event that the overflow yields the expected wrap-around,
_cached_next_run will be negative and the test time >= _cached_next_run will immediately evaluate to true, and continue to do so as long as time is positive.
All these issues can be avoided by using the proper type for timestamps: unsigned long.
The
millis()function returns an unsigned long integer. Implicitly casting it to a signed long is a terrible idea, for several reasons:millis()is set, meaning the cast will result in a negative number, and all theif(time < 0)tests will evaluate to true.last_run + intervalcan overflow, and overflowing a signed number in C++ yields undefined behavior, which is always a bug._cached_next_runwill be negative and the testtime >= _cached_next_runwill immediately evaluate to true, and continue to do so as long astimeis positive.All these issues can be avoided by using the proper type for timestamps: unsigned long.