Skip to content

std::i32::MIN % -1 and related #20

Open
@rcseacord

Description

@rcseacord

do you want to a rule that says used check remainder or make sure that your inputs are not std::i32::MIN % -1
probably std::i32::MIN / -1 and divide by zero as well divide by zero as well

use std::io;
fn main() {
    // Define `i` as the minimum value for a 32-bit signed integer
    let i = std::i32::MIN;
    // Prompt the user for input
    println!("Please enter an integer value for j:");
    // Read input from stdin
    let mut input = String::new();
    io::stdin().read_line(&mut input)
        .expect("Failed to read line");
    // Parse the input as an integer
    let j: i32 = match input.trim().parse() {
        Ok(num) => num,
        Err(_) => {
            eprintln!("Error: Please provide a valid integer for j.");
            std::process::exit(1);
        }
    };
    // Calculate and print the modulus
    println!("i % j = {}", i % j);
}
Exited with status 101
Standard Error
   Compiling playground v0.0.1 (/playground)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.68s
     Running `target/debug/playground`

thread 'main' panicked at src/main.rs:25:28:
attempt to calculate the remainder with overflow
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Standard Output
Please enter an integer value for j:  -1

Lot's of devs don't know about std::i32::MIN % -1, because mathematically it should be zero but faults on Intel processors.

If I ran this on a processor that doesn't fault, would it compile differently?

Compliant solution:

fn main() {
    let i = std::i32::MIN;
    let j = -1;
    match i.checked_rem(j) {
        Some(result) => println!("i % j = {}", result),
        None => println!("i % j = 0"), // This is mathematically correct
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    coding guidelineAn issue related to a suggestion for a coding guidelineenhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions