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

限于喜欢 提交于 2020-01-14 09:59:33

问题


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?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/1161887/what-happens-if-i-cast-a-double-to-an-int-but-the-value-of-the-double-is-out-of

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!