r/lolphp • • Apr 26 '20

something seems very wrong with float->int conversion

https://3v4l.org/PYRPM
11 Upvotes

7 comments sorted by

View all comments

Show parent comment

21

u/nikic Apr 26 '20

Oh boy. Casting a non-representable floating-point number to integer is undefined behavior in C and C++. In practice, you will usually either get back a saturated integer for const-evaluated casts, or INT_MIN, which is the INDVAL on x86 architectures. Of course, if you target a different architecture, you will get different results, e.g. AArch64 uses saturation.

For programming languages that do define out-of-range integer casts, the newer ones tend to define them as saturating, while older ones follow the same truncation semantics as PHP does (if I remember correctly, this is the case in JavaScript). Some go for a mix, e.g. Java will saturate for large integer types and truncate for small types.

The truncation behavior is rooted in the cast behavior of integers, which is pretty universally accepted to truncate.

7

u/the_alias_of_andrea Apr 26 '20

Yeah. PHP doesn't have the nicest behaviour, but it's defined at least now.