when learning about static_cast and dynamic_cast i saw an advice about additional checking on overflow and underflow when casting double type into int one. how can i do that here?
double value1{ 4.8967 };
int value2 = static_cast<int>(value1);
std::cout << value2 << std::endl;
i tried searching here and there only to found an arithmetic over-/underflow which seems not quite the case here. i'd appresiate a couple of links where i can read about it more specifically
You could use std::numeric_limits
create a helper function to avoid overflowing. You'd then get the minimum possible int
value if there would be an underflow or the maximum possible int
value if there would be an overflow.
#include <iostream>
#include <limits> // numeric_limits
template <class R, class T>
R anti_overflow_clamp(T value) {
if (value <= std::numeric_limits<R>::lowest()) [[unlikely]]
return std::numeric_limits<R>::lowest();
if (std::numeric_limits<R>::max() <= value) [[unlikely]]
return std::numeric_limits<R>::max();
return static_cast<R>(value);
}
int main() {
double value1 = -9872034875209384574237698276453978264398576.0;
auto value2 = anti_overflow_clamp<int>(value1);
std::cout << value2 << '\n'; // min value for int
}