5 ms·
Naively, I imagine it's hard to implement (efficient) overflow semantics for integers in C, without any UB. Rust provides operators for [wrapping overflow](http
by c-cube 6y ago
Naively, I imagine it's hard to implement (efficient) overflow semantics for integers in C, without any UB. Rust provides operators for [wrapping overflow](https://doc.rust-lang.org/nightly/std/primitive.isize.html#method.wrapping_add https://doc.rust-lang.org/nightly/std/primitive.isize.html#m...), [saturating overflow](https://doc.rust-lang.org/nightly/std/primitive.isize.html#method.saturating_add https://doc.rust-lang.org/nightly/std/primitive.isize.html#m...), etc. You can't use UB because then the C compiler can miscompile your code.
Semantics of loops might also be tricky. In fact rust struggles with LLVM's optimizer already on some infinite loops because C++ and rust diverge in semantics there.
- CyberRabbi 6y agoThat’s actually trivial using unsigned arithmetic and two’s complement representation for signed integers, its also equally efficient[1]. Unsigned arithmetic is fully defined in c, including checking for overflow. [1] gcc for example generates optimal code when doing checked addition: https://godbolt.org/z/9jnesx https://godbolt.org/z/9jnesx
- c-cube 6y agoBut that's my point; how can you be sure the compiler will emit the right code instead of assuming that the addition does not overflow and then proceed on pruning the test, since overflow on signed integers is not defined?
- ghoward 6y agoYou implement it by using unsigned arithmetic, then checking that the sign bit flipped. See https://git.yzena.com/Yzena/Yc/src/branch/master/include/yc/arith.h#L305-L315 https://git.yzena.com/Yzena/Yc/src/branch/master/include/yc/... . It's a bit more subtle than that, but that is completely devoid of Undefined, Unspecified, and Implementation-Defined Behavior.
- deleted 6y ago[deleted]