Skip to content

Improper use of signed integers #3

@edgar-bonet

Description

@edgar-bonet

The millis() function returns an unsigned long integer. Implicitly casting it to a signed long is a terrible idea, for several reasons:

  1. 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.
  2. last_run + interval can overflow, and overflowing a signed number in C++ yields undefined behavior, which is always a bug.
  3. 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions