What happens if I add double to int, but the double value is out of range?

What happens if I add double to int, but the double value is out of range?

Say I'm doing something like this?

double d = double(INT_MIN) - 10000.0; int a = (int)d; 

What is the value of a? Is it undefined?

+5
c ++ casting
Jul 21 '09 at 21:35
source share
2 answers

Right Quoting from the standard, 4.9, “Undefined behavior if a truncated value cannot be represented in the target type”.

+19
Jul 21 '09 at 21:38
source share
— -
David Thornley has already fully answered this question. However, to handle this situation in your code, you should consider boost numeric_cast .
 double d = double(INT_MIN) - 10000.0; int a = boost::numeric_cast<int>(d); 

This will throw a runtime exception if d too large for int .

+4
Jul 22 '09 at 8:41
source share



All Articles