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:
- Fix the documentation (Fix
int
documentation on overflow (which is UB) reference-en#23) and explain inexperienced programmers what undefined behavior is. - Make the compiler treat signed overflow "correctly", which the GCC family allows by using the
-fwrapv
flag.
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.