And for INT_MIN? The c-faq (http://c-faq.com/misc/sd26.html) says that this approach fails in that case. Is your suggestion to just avoid INT_MIN? If so, that works. :)
Re:Catching Integer Overflows in C
by JoachimSchipper on Tuesday August 02, 2011 @10:52AM
(#2837309)
To be honest, my suggestion is to avoid signed integers, or at least negative signed integers (beyond perhaps -1 for signalling errors). I find that I almost never need them, and unsigned integers are much nicer to work with.
That's an interesting perspective, and one that probably works out in practice most of the time. Integration with other libs is the place I'm thinking where it doesn't, but it seems simple, and rather trivial in many cases to do the conversion to signed integers before making the library call. Of course, if you're taking advantage of the extra positive values and need a signed int, I think you're shit out of luck.
I've used this approach in one of my school assignments. The result (macros) weren't so nice but I think they've worked. It was few years back so I'm not so sure now.
https://github.com/rplnt/personal/blob/master/C/fractions/zl...
The return value of 1 is strange, but superficial. It's easy enough to replace that with arbitrary behavior. The advantage of the approach in the OP is that it is more agnostic about the types involved, leading to more flexible code.
The proper way to do this is still
and variants.