6 ms·
Some undefined behaviours relate to runtime values. !iirc! signed 2+2 is safe but signed SIGNED_INT_MAX + 1 is not.
by chrisdew 9y ago
Some undefined behaviours relate to runtime values. !iirc! signed 2+2 is safe but signed SIGNED_INT_MAX + 1 is not.
- Peaker 9y agoBut it is easy to give it a defined behavior on a particular architecture. For example, on x86-64, it can be defined to overflow just like unsigned does. The compiler can emit errors about the code if it is compiled to a different architecture where the same defined behavior is too expensive to implement.
- scatters 9y agoHow would that help? The behavior would be defined, but it still wouldn't be what you /want/.
- Peaker 9y agoDefined good behavior > defined bad behavior > undefined behavior. This article is about attacking the last category. Unsigned overflow is far less of a problem than signed overflow because it is defined. It is very cheap to make signed overflow defined. It is more expensive to detect it and fail at runtime.
- petergeoghegan 9y agoIt can be, but it isn't. All contemporary ISAs use two's complement arithmetic for signed integers, including x86-64, and so I think signed overflow could be made well defined on all archs without particularly disadvantaging one arch over the other. The reason that that doesn't happen, here as elsewhere, is that there are a number of specific compiler optimizations that rely on it being undefined. See GCC's -fwrapv flag.