D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 22527 - Casting out-of-range floating point value to signed integer overflows
Summary: Casting out-of-range floating point value to signed integer overflows
Status: RESOLVED FIXED
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: All All
: P1 normal
Assignee: No Owner
URL:
Keywords: pull
Depends on:
Blocks:
 
Reported: 2021-11-19 04:59 UTC by Paul Backus
Modified: 2021-12-14 17:14 UTC (History)
2 users (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description Paul Backus 2021-11-19 04:59:58 UTC
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 moonlightsentinel 2021-11-19 13:03:18 UTC
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 SorinM 2021-12-10 23:16:11 UTC
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 Dlang Bot 2021-12-10 23:23:24 UTC
@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 Dlang Bot 2021-12-14 17:14:14 UTC
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