Handling overflow when casting doubles to integers in C

后端 未结 9 2037
耶瑟儿~
耶瑟儿~ 2020-12-09 08:24

Today, I noticed that when I cast a double that is greater than the maximum possible integer to an integer, I get -2147483648. Similarly, when I cast a double that is less

相关标签:
9条回答
  • 2020-12-09 09:17

    I can't tell you for certain whether it is defined for all platforms, but that is pretty much what's happened on every platform I've used. Except, in my experience, it rolls. That is, if the value of the double is INT_MAX + 2, then when the result of the cast ends up being INT_MIN + 2.

    As for the best way to handle it, I'm really not sure. I've run up against the issue myself, and have yet to find an elegant way to deal with it. I'm sure someone will respond that can help us both there.

    0 讨论(0)
  • 2020-12-09 09:23

    limits.h has constants for max and min possible values for integer data types, you can check your double variable before casting, like

    if (my_double > nextafter(INT_MAX, 0) || my_double < nextafter(INT_MIN, 0))
        printf("Overflow!");
    else
        my_int = (int)my_double;
    

    EDIT: nextafter() will solve the problem mentioned by nwellnhof

    0 讨论(0)
  • 2020-12-09 09:23

    Another option is to use boost::numeric_cast which allows for arbitrary conversion between numerical types. It detects loss of range when a numeric type is converted, and throws an exception if the range cannot be preserved.

    The website referenced above also provides a small example which should give a quick overview on how this template can be used.

    Of course, this isn't plain C anymore ;-)

    0 讨论(0)
提交回复
热议问题