RandomUser123
RandomUser123

Reputation: 77

Visual Studio (MASM) assembly - why does code in labels automatically execute, even if label not called

So I have this code and both labels are being executed, even though I was under the impression they would only execute if called with a jmp instruction

In other words, the output of this code is 15 - i.e. 5 + 7 + 3, while I thought it should be 5, since the labels aren't being called via the jmp instruction

.data
    
.code

TestNew proc
    mov rax, 5

    lbl1:
        add rax, 7

    lbl2:
        add rax, 3

    ret

TestNew endp
end

It seems the jmp instruction is working, since if I call it e.g. here, I get an infinite loop:

.data
    
.code

TestNew proc
    mov rax, 5

    lbl1:
        add rax, 7

    lbl2:
        add rax, 3

    jmp lbl1 ;causes infinite loop...so at least jmp is working
    ret

TestNew endp
end

If anyone could give me any tips on how to get this working, I'd appreciate it.

Thanks

Upvotes: 2

Views: 583

Answers (1)

Nate Eldredge
Nate Eldredge

Reputation: 58142

even though I was under the impression they would only execute if called with a jmp instruction

Sorry, your impression is mistaken. Labels are not analogous to functions or subroutines in a higher-level language. They are just, well, labels: they give a human-readable name to a particular address in memory, but do not have any effect on what is actually in that memory.

Labels can be used to mark the beginning of a subroutine or block of code, so that you can call or jump to it by name from elsewhere. But whatever code immediately precedes your subroutine will by default fall through into it, so you normally have to put a jump or return or some similar instruction there if fall-through is not what you want. Likewise, in order to get your subroutine to return, you code an actual ret instruction; merely inserting a label to start the next subroutine would again result in fall-through.

Execution in assembly always flows from one instruction to the next one that follows it in memory, unless the instruction is a jump or call or some other whose purpose is to redirect execution flow. Putting labels between two instructions does not alter that principle in any way.

So yes, your code is always going to execute the mov and then the two adds, since you have not coded any jump instruction that would alter this.

Upvotes: 3

Related Questions