Will the compiler optimize this code that sometimes has no effect?

    let mut a = 1;
    let b = some_random_int_between_1_and_5;
    a = 
        if b > 2 {
            a
        } else {
            b
        };
    println!("a is the same: {}", a);

Depending on the value of b, the above code might not have any effect on a. Will the optimizer generate a non instruction in these cases or will it copy a to a?

This

pub fn foo(b: i32) -> i32 {
    let mut a = 1;
    a = if b > 2 {
        a
    } else {
        b
    };
    a
}

generates the assembly

example::foo:
  cmp edi, 2
  mov eax, 1
  cmovle eax, edi
  ret

As you can see, it uses the cmovle instruction, which is short for "conditional move if less or equal", which either leaves a unchanged, or replaces it with b depending on the result of the comparison earlier in the assembly.

Since there is no branching in the resulting machine code, the answer to your question is that neither of the two options is the case.

1 Like

You can use godbolt to easily check the assembly of snippets, and cargo asm for your actual code.

godbolt.org/

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.