5 ms·
I'm not a fan of this approach - did you notice that addition, for instance, just returns 1(!) instead of overflowing? The proper way to do this is still
by JoachimSchipper 15y ago
I'm not a fan of this approach - did you notice that addition, for instance, just returns 1(!) instead of overflowing?
The proper way to do this is still
if (a > UINT_MAX - b)
errx(1, "Too large.");
a += b;
and variants.
- apgwoz 15y agoAnd for INT_MIN? The c-faq (http://c-faq.com/misc/sd26.html 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. :)
- JoachimSchipper 15y agoTo 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.
- apgwoz 15y agoThat'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.
- rplnt 15y agoI'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/zlomek.h#L10 https://github.com/rplnt/personal/blob/master/C/fractions/zl...
- Estragon 15y agoThe 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.