Bug 22527 – Casting out-of-range floating point value to signed integer overflows

Status
RESOLVED
Resolution
FIXED
Severity
normal
Priority
P1
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2021-11-19T04:59:58Z
Last change time
2021-12-14T17:14:14Z
Keywords
pull
Assigned to
No Owner
Creator
Paul Backus

Comments

Comment #0 by snarwin+bugzilla — 2021-11-19T04:59:58Z
As of DMD 2.098.0, the following program fails to compile: --- static assert(cast(int) float.max > 0); --- The error message is: --- Error: static assert: `-2147483648 > 0` is false --- According to the language spec: > Casting a floating point value to an integral type is the equivalent of converting to an integer using truncation. Since float.max is a positive number, truncation of its value should result in a positive integer, not a negative integer.
Comment #1 by moonlightsentinel — 2021-11-19T13:03:18Z
The problem here is that the integral value of float.max exceeds int.max, so it's a truncation followed by an integer overflow.
Comment #2 by sorin.mateescu — 2021-12-10T23:16:11Z
Compiling this example in C: ``` #include <float.h> int main() { float f = FLT_MAX; int i = (int)f; return 0; } ``` and then looking into the assembly, you can see the cvttss2si instruction is used to perform the cast. Reading from the second paragraph of https://www.felixcloutier.com/x86/cvttss2si#description we can find the answer: 80000000H (or INT_MIN) is the result in case of floating-point invalid exception. As this is defined directly in the x86 ISA and is the default behavior in C, this will also be the case for D.
Comment #3 by dlang-bot — 2021-12-10T23:23:24Z
@sorin-gabriel created dlang/dlang.org pull request #3140 "fix Issue 22527 - Casting out-of-range floating point value to signed…" fixing this issue: - fix Issue 22527 - Casting out-of-range floating point value to signed integer overflows https://github.com/dlang/dlang.org/pull/3140
Comment #4 by dlang-bot — 2021-12-14T17:14:14Z
dlang/dlang.org pull request #3140 "fix Issue 22527 - Casting out-of-range floating point value to signed…" was merged into master: - 05cb1035324a62ffab1467fad7eea8d68ca41520 by Gabriel: fix Issue 22527 - Casting out-of-range floating point value to signed integer overflows https://github.com/dlang/dlang.org/pull/3140