Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

casting

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

Lets say I do something like this?

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

What is the value of a? Is it undefined?

like image 694
Roland Rabien Avatar asked Jul 21 '09 21:07

Roland Rabien


2 Answers

Precisely. Quoting from the Standard, 4.9, "The behavior is undefined if the truncated value cannot be represented in the destination type."

like image 147
David Thornley Avatar answered Nov 11 '22 01:11

David Thornley


David Thornley answered this question completely already. However to deal with this situation in your code you should consider boost's numeric_cast.

double d = double(INT_MIN) - 10000.0;
int a = boost::numeric_cast<int>(d);

This will throw an exception at runtime if d is too big for an int.

like image 42
iain Avatar answered Nov 11 '22 01:11

iain