Search code examples
functionassemblyx86callintel

Jump and Call on same line in assembly


I want to know if there is a way to make a conditional decision and call a function based on that result.

For example. I want to compare something. I want to do the function call if they are even. However, the way I wrote my function I need to call the function and not jump to it. (based on the way my function handles the stack) Is there a way to do that? I have copied my code in as shown, it does not compile.

.endOfForLoop: cmp  dword [ebp - 4], 1 ; compares the boolean to one
je call print_prime ; if it is one then prime needs to be printed
jmp call print_not_prime ; otherwise it is not prime

Using NASM, x86 32 bit assembly, linux, intel


Solution

  • Just jump around the function call as if you'd implement an if-then-else:

    .endOfForLoop:
        cmp dword [ebp-4],1
        jne .not_prime
        call print_prime
        jmp .endif
    .not_prime:
        call print_not_prime
    .endif:
    

    You could also use function pointers and the cmov instruction to make your code branchless, but I advise against writing code like this as it is harder to understand and not actually faster as all branch predictors I know do not try to predict indirect jumps at all.

    .endOfForLoop:
        cmp dword [ebp-4],1
        mov eax,print_prime
        mov ebx,print_not_prime
        cmovne eax,ebx
        call eax