C++ vs Rust ( This is not a fight area :) )

⚓ Rust    📅 2025-12-01    👤 surdeus    👁️ 2      

surdeus

Hello,

I tried to compare simple C++ and Rust fonction:
In C++, a simple function like:

int add(int a, int b) {
    return (a*b)/b;
}

Gives the following asm:

add(int, int):
        mov     eax, edi
        ret

I now that the C++ compiler used UB to optimize le following which is ok here.

In Rust, the same code:

pub fn square(num: i32, fac: i32) -> i32 {
    (num*fac)/fac
}

Gives the following asm:

square:
        push    rax
        test    esi, esi
        je      .LBB0_3
        imul    edi, esi
        mov     eax, esi
        not     eax
        lea     ecx, [rdi - 2147483648]
        or      ecx, eax
        je      .LBB0_2
        mov     eax, edi
        cdq
        idiv    esi
        pop     rcx
        ret

Is there a way to ask rustc to ignore overflow and div by 0 because we now we will never have it or we don't care in our program? like a game.

Thank you,

10 posts - 9 participants

Read full topic

🏷️ Rust_feed