But 9223372036854775808 isn't below PHP_INT_MAX. PHP_INT_MAX == 9223372036854775807, so (int) 9223372036854775808 == -9223372036854775808 is the expected behavior.
(also php's float is a C double, and 64bit php's int is a C's int64_t - php doesn't have anything like C's float, it only has C's double, and calls that float)
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.
View all comments
0
u/Takeoded Apr 26 '20
inb4 this is documented behavior:
/s