Is there some meaningful statistical data to justify keeping signed integer arithmetic overflow undefined?

I don’t know about studies and statistics, but yes, there are definitely optimizations taking this into account that compilers actually do. And yes, they are very important (tldr loop vectorization for example). Besides the compiler optimizations, there is another aspect to be taken into account. With UB you get C/C++ signed integers to behave arithmetically … Read more

How can I detect integer overflow on 32 bits int?

Math.addExact throws exception on overflow Since Java 8 there is a set of methods in the Math class: toIntExact(long) addExact(int,int) subtractExact(int,int) multiplyExact(int,int) …and versions for long as well. Each of these methods throws ArithmeticException if overflow happens. Otherwise they return the proper result if it fits within the range. Example of addition: int x = … Read more

-1 * int.MinValue == int.MinValue?? Is this a bug?

This is not a bug. int.MinValue * -1 is 1 greater than int.MaxValue can hold. Thus, the number wraps around back to int.MinValue. This is basically caused by an integer overflow. Int32.MinValue: The value of this constant is -2,147,483,648 Int32.MaxValue: The value of this constant is 2,147,483,647 So, -2,147,483,648 * -1 = 2,147,483,648 which is … Read more

Why don’t languages raise errors on integer overflow by default?

In C#, it was a question of performance. Specifically, out-of-box benchmarking. When C# was new, Microsoft was hoping a lot of C++ developers would switch to it. They knew that many C++ folks thought of C++ as being fast, especially faster than languages that “wasted” time on automatic memory management and the like. Both potential … Read more

Does integer overflow cause undefined behavior because of memory corruption?

You misunderstand the reason for undefined behavior. The reason is not memory corruption around the integer – it will always occupy the same size which integers occupy – but the underlying arithmetics. Since signed integers are not required to be encoded in 2’s complement, there can not be specific guidance on what is going to … Read more

Compiler optimizations may cause integer overflow. Is that okay?

As Miles hinted: The C++ code text is bound by the rules of the C++ language (integer overflow = bad), but the compiler is only bound by the rules of the cpu (overflow=ok). It is allowed to make optimizations that the code isn’t allowed to. But don’t take this as an excuse to get lazy. … Read more

Can argc overflow?

According to the standard So, from your quote: argv[argc] is required to be a null pointer Therefore, argc cannot overflow, because then the above statement would not be true. In practice In practice, the total size of the arguments passed to a program is limited. On my Linux/x64 system: $ getconf ARG_MAX 2097152 Therefore, the … Read more