6 ms·
This issue could be even harder to detect with a generic Abs function. It would work on floats (I think?) and on almost all ints, but it would have edge case fa
by bumbledraven 5y ago
This issue could be even harder to detect with a generic Abs function. It would work on floats (I think?) and on almost all ints, but it would have edge case failures on certain ints.
- beached_whale 5y agoIn C++ you would so something like if constexpr( std::is_unsigned_v<Number> ) { return x; } else { if( x >= 0 ) { return x; } if( x <= -std::numeric_limits<Number>::max( ) ) { // What do we return?? } return -x; } This comes up in parsing too. One often will harden against signed overflow by using an unsigned type and then multiplying the sign at the end. One needs to check for these kinds of things when the type is the biggest, like intmax_t(generally int64_t)
- jepler 5y agoYou can also (except this is awful!) work in the space of negative numbers through almost all of parsing and then, unless the sign is "-", negate the value just before returning it. However, having a base unsigned parsing routine and then doing signed conversion including application of unary +/- sign to the number at the very end allows sharing the most code.
- beached_whale 5y agoThe issue is that overflow on signed is UB. I can count final decimal places(ptr - start_ptr) to check if it is larger than the maximum digits allowed. This is cheap as the check is after the parse. Throw in a floor(log10( result )) == diff or something like that too.