Handling overflow when casting doubles to integers in C

后端 未结 9 2058
耶瑟儿~
耶瑟儿~ 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: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 ;-)

提交回复
热议问题