0

Following is the c++ code;

int func1(int i) {return i*7;}
int func2(int i) {return i*11;}

int test(int i){
    int j;
    if(i>0) {
        j = func1(i);
    }else {
        j = func2(i);
    }
    return j*13;
}

The instructions for above code (Ignoring func1 and func2 instructions) in debug mode comes out to be

test(int):
  push rbp
  mov rbp, rsp
  sub rsp, 24
  mov DWORD PTR [rbp-20], edi
  cmp DWORD PTR [rbp-20], 0
  jle .L6
  mov eax, DWORD PTR [rbp-20]
  mov edi, eax
  call func1(int)
  mov DWORD PTR [rbp-4], eax
  jmp .L7
.L6:
  mov eax, DWORD PTR [rbp-20]
  mov edi, eax
  call func2(int)
  mov DWORD PTR [rbp-4], eax
.L7:
  mov edx, DWORD PTR [rbp-4]
  mov eax, edx
  add eax, eax
  add eax, edx
  sal eax, 2
  add eax, edx
  leave
  ret

Please help me in understanding on what happens post jump to .L6 instruction; Will it Go directly to .L7 or will it execute the instructions after .L6 and then go to .L7; If it later then seems like its executing both the loop conditions.

Godbolt link.

  • Compile your code with `g++ -Wall -fverbose-asm -S -O2` – Basile Starynkevitch May 04 '20 at 04:29
  • 1
    [The compiler explore to the rescue](https://godbolt.org/z/da0VHy). It shows you exactly which part of the generated assembly belongs to which statement. – Some programmer dude May 04 '20 at 04:33
  • Single-step the code in a debugger to see how execution always proceeds to the next instruction (except on call or jmp instructions), and falls through labels. – Peter Cordes May 04 '20 at 04:40
  • I think you're just asking if labels are magic. They aren't, they're just a way for jump instructions to refer to positions in code, like I explained in my answer to a similar quesiton: [What if there is no return statement in a CALLed block of code in assembly programs](https://stackoverflow.com/q/41205054) – Peter Cordes May 04 '20 at 05:03
  • Well thats where my follow up question comes up; That the assembly code shows the execution of .L7 after executing .L6; The responsible code is if-else condition so only one of them shall be executed. So on execution of first branch, it also executes the second branch as per the assembly code - which is confusing to me. Was seeking answer for that. Thanks. – Radheshyam Bang May 04 '20 at 05:13
  • 1
    The first branch is the 5 instructions before .L6 and the second branch is the instructions between .L6 and .L7. – eesiraed May 04 '20 at 06:08
  • @BessieTheCow: exactly. And the only *conditional* branch is the `jle .L6` - the `jmp` is avoiding executing the `else` side as well. – Peter Cordes May 04 '20 at 07:28

0 Answers0