Unexpected value when using remainder operation.
I tried this code:
extern "C" {
fn printf(s: *const i8, ...);
}
fn print_int(value: i8) {
let s = "%d\n\0";
let s_p = s as *const str;
let c_p = s_p as *const i8;
unsafe {
printf(c_p, value);
}
}
fn main() {
let mut checksum: i8 = -30_i8 % -55_i8;
print_int(checksum);
}
I expected to see this happen: -30
Instead, this happened: 226
Meta
- What version of Rust GCC were you using, git sha if possible. gccrs (GCC) 12.0.1 20220118 (experimental) git sha: 9d81164aa0447c738fe0435de14ec9666a03d5da
I don't think the error is related to remainder operation. If you change the printf line to printf(c_p, value as isize);, the output will be -30. My understanding is that printf treats value as a normal integer. -30 and 226 have the same binary representation (0xe2). If you try to compile this program with rustc, you get this error:
error[E0617]: can't pass `i8` to variadic function
--> remainder.rs:10:21
|
10 | printf(c_p, value);
| ^^^^^ help: cast the value to `c_int`: `value as c_int`
error: aborting due to previous error
So it does appear that the issue is not remainder operation but actually displaying the number using printf.
This looks like a duplicate of #1495 @philberty
The given code now produces this error:
<source>:10:21: error: expected 'c_int' variadic argument
10 | printf(c_p, value);
| ^~~~~
https://godbolt.org/z/nv9YqnGcP