4 ms·
This has nothing to do with C programming. If an arithmetic operation could overflow, you always have to add a check regardless of programming language. It's si
by nwellnhof 6y ago
This has nothing to do with C programming. If an arithmetic operation could overflow, you always have to add a check regardless of programming language. It's simply that a lot of high-level code doesn't care about such a level of correctness. Another exception are languages like Python that automatically upgrade your integers to arbitrary precision on overflow.
That said, most of the time you end up counting objects in the current address space. If you assume that there can exist no more than `SIZE_MAX` objects in memory, you can avoid many overflow checks.
- dgellow 6y agoMy question does have to do with C programming. Other languages (not C++ of course) do not have signed overflow considered an undefined behaviour. My question is specifically about this.
- nwellnhof 6y agoThe point is that integer overflow practically always indicates a programming error. How a certain languages handles integer overflows is secondary. These overflows shouldn't happen in the first place. Making overflows a well-defined operation actually hides programming errors. With regard to C compilers, there are a few cases where a compiler performs optimizations because it assumes signed integer overflow cannot happen. This is bad but typically, compiled C behaves like the underlying platform which means signed integers wrap around. With GCC, you can enforce this behavior and make signed integer overflow a defined operation with `-fwrapv`. You can also compile your code with UBSan to get runtime checks during testing. UBSan can also check for unsigned integer overflow which is defined behavior in C. So with modern C compilers, the situation is basically the same as with Rust, Zig or other safer languages.