Handling overflow when casting doubles to integers in C

后端 未结 9 2061
耶瑟儿~
耶瑟儿~ 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:05

    A portable way for C++ is to use the SafeInt class:

    http://www.codeplex.com/SafeInt

    The implementation will allow for normal addition/subtract/etc on a C++ number type including casts. It will throw an exception whenever and overflow scenario is detected.

    SafeInt s1 = INT_MAX;
    SafeInt s2 = 42;
    SafeInt s3 = s1 + s2;  // throws
    

    I highly advise using this class in any place where overflow is an important scenario. It makes it very difficult to avoid silently overflowing. In cases where there is a recovery scenario for an overflow, simply catch the SafeIntException and recover as appropriate.

    SafeInt now works on GCC as well as Visual Studio

提交回复
热议问题