Handling overflow when casting doubles to integers in C

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

    To answer your question: The behaviour when you cast out of range floats is undefined or implementation specific.

    Speaking from experience: I've worked on a MIPS64 system that didn't implemented these kind of casts at all. Instead of doing something deterministic the CPU threw a CPU exception. The exception handler that ought to emulate the cast returned without doing anything to the result.

    I've ended up with random integers. Guess how long it took to trace back a bug to this cause. :-)

    You'll better do the range check yourself if you aren't sure that the number can't get out of the valid range.

提交回复
热议问题