Hello all,
Iāve stumbled upon yet another bug in C++ code due to mixing signed and unsigned types, and decided to check how it might be handled in Rust.
Actually, Iām a bit surprised.
fn main() {
let a = -2;
let b:u32 = 2;
let c = a / b;
println!("{} / {} = {}", a, b, c);
}
Output
<anon>:2:10: 2:12 error: unary negation of unsigned integers may be removed in the future
<anon>:2 let a = -2;
^~
error: aborting due to previous error
So far so good, but it looks like a special case. Minor changes and we got a terrible result of mixing signed and unsigned types.
fn main() {
let a = 2;
let b = 6;
let c:u32 = 2;
let d = (a - b) / c;
println!("({} - {}) / {} = {}", a, b, c, d);
}
Output
(2 - 6) / 2 = 2147483646
Why such unsafe code is possible in such safe language?
Also, it is hard to reason about a piece of code like let a = 2, as it is not possible to know whether a is signed or unsigned.
Thank you