Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Signed overflow not always wrapping correctly #4511

Closed
Labels
@cousteaulecommandant

Description

Summary: Please consider adding the -fwrapv flag to the list of flags passed to Arduino's compiler. It fixes potential undefined behavior an Arduino user should not deal with.


  • According to the Arduino documentation, when an int exceeds its limit value it "rolls over" (wraps) to the other side, modulo 2^16 (or 2^32).
  • According to the C++ standard, when a signed integer such as int exceeds its limit value it triggers "undefined behavior" and the implementation is free to go crazy when it happens (doing this with unsigned integers is fine though).
  • According to GCC, taking care of undefined behavior is none of its business and can neglect it for the sake of efficiency (e.g. when the optimization flag -O2 is used).

As a result, code such as this acts weird, and might catch someone off-guard:

bool will_overflow(int x) {
 int y = x+1;
 return y < x; // compiler assumes this will never happen => will always return false
}
 will_overflow(INT_MAX) // returns false instead of true, even though INT_MAX+1 overflows

The GCC-based compiler used by Arduino warns about this when you enable the -Wall flag (which is disabled by default in Arduino):
sketch.ino: warning: assuming signed overflow does not occur when assuming that (X + c) < X is always false [-Wstrict-overflow]

There are 2 ways to fix this:

In general I'm against "fixing" bugs by documenting them (although technically this is not a bug), plus the current behavior is rather counter-intuitive and hard to understand for people with a basic notion of how binary works, so I think the best solution is to fix this in a user-friendly way, i.e. adding the -fwrapv flag.

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

        AltStyle によって変換されたページ (->オリジナル) /