How many CPU operations programming languages use for % and fmod()?

29 Views Asked by At

What is the result of C translation for % operator and fmod() function in machine language? What is it's implementation?

For example: Will 61199 % 256 be solved the same way as 61199 % 171?

1

There are 1 best solutions below

0
VLL On

If the platform supports integer division, like all modern non-embedded processors, it is a single instruction. The division instruction gives the quotient and the remainder.

Consider this C program (https://godbolt.org/z/vxj8fKdjG):

int main() {
    int a = 61199;
    int b = 171;
    int c = a % b;
}

It compiles to:

main:
        push    rbp
        mov     rbp, rsp
        mov     DWORD PTR [rbp-4], 61199
        mov     DWORD PTR [rbp-8], 171
        mov     eax, DWORD PTR [rbp-4]
        cdq
        idiv    DWORD PTR [rbp-8]
        mov     DWORD PTR [rbp-12], edx
        mov     eax, 0
        pop     rbp
        ret

In this output idiv is the division instruction.