Rust: Integer division/remainder rounding behavior should be documented

Created on 7 Jul 2015  ·  3Comments  ·  Source: rust-lang/rust

Using Google I can find lots of old arguments over how integer division should work in Rust, but I cannot find anything in the reference, the API docs for the integer types, or the API docs for the Div trait that says what was actually decided. (And the documentation seems to imply that /, checked_div, and wrapping_div may not all do the same thing.) This is further confused by the integer type documentation apparently sometimes using / to refer to integer division and sometimes to mathematical division. (I can't come up with out any other reasonable interpretation of floor(self / other) in the wrapping_div documentation.) It would be nice if this were clearly documented somewhere, since this varies between languages and is one of the main confusions with integer arithmetic.

All 3 comments

http://doc.rust-lang.org/reference.html#behavior-not-considered-unsafe talks about 'overflow' and mentions wrapping, but you're right that we can surface this better.

@steveklabnik

This is about rounding, not wrapping. We use LLVM's sdiv, which rounds towards zero (and srem has the same sign as the dividend). We should document this (the documentation for wrapping_div currently _lies_, claiming that it rounds towards negative infinite).

This should also leave a warning, because integer / integer is not always desired and happens by accident. Just a thought if anyone is reading this.

Was this page helpful?
0 / 5 - 0 ratings