4 ms·
Of course you gain ability to check for overflow after performing the operation, Using exceptions? IMHO only very small fraction of overflow bugs would have b
by cautious_int 11y ago
Of course you gain ability to check for overflow after performing the operation,
Using exceptions?
IMHO only very small fraction of overflow bugs would have been fixed by just wrapping result around.
Yes, switching to wrapping integers is not the solution to overflow. Rather check the operation beforehand. I still think using unsigned integers is always preferred if you don't need negative values.
- wuch 11y agoWhat I had in mind, is the fact that with defined overflow you could unconditionally perform the operation, and then observe the result to decide if overflow have in fact happened. For example, following pattern to check if adding 100 to an integer 'a' overflows would be valid: int a = ...; if (a + 100 < a) overflow So this is one of cases where wrapping behaviour could potentially fix bugs in existing applications. Obviously, rewriting this to work with overflow is trivial if you are already aware of undefined behaviour that could occur.
- cautious_int 11y agoHow would that fix existing code without modifying it?
- wuch 11y agoSuppose somebody have written above code. Then under current C++ standard it would invoke UB on overflow. But, if standard were to change and require wrapping behaviour for int, then it would be "fixed", i.e, do what programmer intended it to do. Similarly if you use some compiler specific option to ensure wrapping behaviour for signed integers like GCC -fwrapv.
- cautious_int 11y agoOh, you are assuming someone actually wrote that code. That is circular reasoning. It would be much better to write proper checks or just call functions that do so.