-
-
Notifications
You must be signed in to change notification settings - Fork 7k
Signed overflow not always wrapping correctly #4511
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Adding |
(also, thanks for the well-explained and researched request!) |
Fix for issue arduino#4511 In short, the documentation says that signed integer overflow causes the value to "roll over". Actually, this results in undefined behavior, with potentially unpredictable results. This patch adds a GCC option to treat signed integers the "right" way so that they roll over as the documentation claims.
Well, since I didn't see much motion I decided to make my own PR to see if it's correct and it gets accepted |
It's been many years since I tracked this down, but an issue that I've run into is that on the AVR, the compiler is inconsistent in how it treats char vs unsigned char and signed char when the signs match. I wonder if this option would resolve this to make things consistent? |
I've edited the "int" page and removed the wrong indication about rollover: http://edit.arduino.cc/en/Reference/Int So the reference is ok now. Let's continue on |
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.int
exceeds its limit value it "rolls over" (wraps) to the other side, modulo 2^16 (or 2^32).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).-O2
is used).As a result, code such as this acts weird, and might catch someone off-guard:
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:
int
documentation on overflow (which is UB) reference-en#23) and explain inexperienced programmers what undefined behavior is.-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.The text was updated successfully, but these errors were encountered: