Hi! On Wed, Dec 18, 2019 at 11:04:07AM +0100, David Brown wrote: > In practice, often you can write code that is portable > to any "reasonable" implementation, and accept that the code won't work > for other systems: > > #include <limits.h> > #if -INT_MAX == INT_MIN > #error Only two's complement signed integers supported by this code > #endif (And hopefully document it, and/or even do a test like you did here). > > 0. Conversion a value from `unsigned int` to `signed char` which doesn't > > fit in it yields an implementation-defined result. > > [C++14 now requires 2's complement, which is required by GCC.] > > IIRC it is C++20 that limits the signed integer representation to two's > complement. Yes, that is my understanding as well. > Note that it is entirely possible for an implementation to have two's > complement representation but /not/ use modulo to reduce a value to fit > into a smaller signed type. In particular, a compiler could choose to > raise a signal and halt with an error message (I don't know if any of > gcc's sanitizers do that). -fsanitize=signed-integer-overflow (part of -fsanitize=undefined, ubsan). [ lots of good stuff snipped ] > When you write some code, you first figure out what the code should do. > Then you can think about what range of systems it makes sense to > support. Portable coding is then usually fairly easy as long as the > target range is sensible. Yes, exactly. And the only good way to avoid undefined behaviour is simply to know what not to do. C is not a friendly language to beginners, in that sense. Segher