Skip to content

Commit 0b79630

Browse files
committed
add another example for what this means for const
1 parent ef1b0bf commit 0b79630

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

text/0000-float-semantics.md

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,6 @@ However, the exact function is not specified, and it is allowed to change across
9797
In particular, there is no guarantee that the choice made in const evaluation is consistent with the choice made at runtime.
9898
That is, the following assertion is allowed to fail (and in fact, it [fails on current versions of Rust](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=a594d2975c29b1c7fa457a4ec4ae4b87)):
9999
```rust
100-
#![allow(non_snake_case)]
101100
use std::hint::black_box;
102101

103102
const C: f32 = 0.0 / 0.0;
@@ -111,6 +110,22 @@ fn main() {
111110
This means that evaluating the same `const fn` on the same arguments can produce different results at compile-time and run-time.
112111
However, note that these functions are already non-deterministic: even evaluating the same function with the same arguments twice at runtime can [and does](https://play.rust-lang.org/?version=stable&mode=release&edition=2021&gist=50b5a549fa1fe259cea5ad138066ccf0) produce different results!
113112

113+
In other words, consider this code:
114+
```rust
115+
const fn div(x: f32) -> i32 {
116+
unsafe { std::mem::transmute(x / x) }
117+
}
118+
119+
// This is not guaranteed to always succeed. That's new, currently
120+
// all `const fn` you can write guarantee this.
121+
assert_eq!(div(0.0), div(0.0));
122+
// Consequently, different results can be observed at compile-time and at run-time.
123+
const C: i32 = div(0.0);
124+
assert_eq!(C, div(0.0));
125+
```
126+
The first assertion is very unlikely to fail in practice (it would require the two invocations of `div` to be optimized differently).
127+
The second however [actually fails](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=0b4b952929c9ebcd2bd50aee54e6cdf4) on current nightlies in debug mode.
128+
114129
This resolves the last open question blocking floating-point operations in `const fn`.
115130
When the RFC is accepted, the `const_fn_floating_point_arithmetic` feature gate and the `const fn to_bits` methods can be stabilized.
116131

0 commit comments

Comments
 (0)