Reputation: 3
I tried searching for an answer to this and the examples with any similarity at all were either too simple or too complex. I'm using Paul Carter's book for an assembly class, so some of the macros are from him. Namely, the print_string, print_int, and print_nl functions.
Given this snippet of assembly:
segment .data
output db "Welcome!",0
string1 db "greater than",0
string2 db "less than",0
string3 db "equal to",0
var_a dd 0Ah
segment .bss
segment .text
global _asm_main
_asm_main:
enter 0,0 ; setup routine
pusha
;***************CODE STARTS HERE***************************
mov eax, output
call print_string
call print_nl
cmp dword[var_a], 0Ah
jle label1
mov eax, string1
call print_string
call print_nl
jmp label3
label1:
cmp dword[var_a], 9h
jg label2
mov eax, string2
call print_string
call print_nl
jmp label3
label2:
mov eax, string3
call print_string
call print_nl
label3:
cmp dword [var_a], 0
jle label4
sar [var_a], 1
mov eax, dword [var_a]
call print_int
call print_nl
jmp label3
label4:
;***************CODE ENDS HERE*****************************
popa
mov eax, 0 ; return back to C
leave
ret
The output is:
Welcome!
equal to
5
2
1
0
My question:
I see how it eventually gets to label2 via the comparisons, prints the "equal to" message and a new line. After that though, I see no additional comparisons in label2. At that point, how does label3 even get invoked? How does the program "leave" label2? I understand everything in the assembly except in between the end of label2 (which prints the "equal to") and the start of label3 (where it loops a bit shift and prints the numbers). Am I missing something?
After label2 is executed, does control of the program go back to where label2 was first called in label1? Or does label3 execute because it's next sequentially?
Upvotes: 0
Views: 1526
Reputation: 18552
Imagine that your code had no labels at all. The machine would execute instructions one by one, going down the list. Adding labels does not change this behavior at all; the machine will still go to the next instruction unless there's a jump.
A label gives a name to a memory address. They are useful when jumping. If we didn't have labels, then we might need to do something like this:
add foo, bar
sub foo, bar
mul foo, bar
jmp -2 ; Fake code for "go up 2 instructions"
With labels, we can give names to the memory address of an instruction:
add foo, bar
thingamajig: ; This label equals the address of the 'sub' instruction
sub foo, bar
mul foo, bar
jmp thingamajig
Upvotes: 2