Reputation: 8577
I read a book about assembly, which have the next code. The code comapre (lexcially) two arrays (int value), and return 1 if the first is bigger, 0 if it equal or -1 otherwise:
Comprator:
push ebp
mov ebp, esp
mov esi, [ebp+8] ; first - A
mov edi, [ebp+12] ;Second - B
mov ecx, [ebp+16]
comp esi,edi,ecx
jl less
je equal
mov eax, 1
jmp end
equal:
mov eax,0
jmp end
less:
mov eax, -1
jmp end
end:
pop ebp
ret
%macro comp 3
mov ecx, %3
%%l:
mov eax,[%1]
mov ebx,[%2]
cmp eax,ebx
jne %%done
add %1, 4
add %2, 4
loop %%l
sub eax,eax
%%done:
%endmacro
I don't undestand why it needs the line: sub eax,eax
. If we have two identical arrays, so in the last compare, we would get, for example, cmp 3,3
- then we will exit from the loop, and for the line je equal
- it will return true, and would jump to end.
Upvotes: 1
Views: 2587
Reputation: 490408
It's to set the Z flag so the je equal
after the macro will know that the two arrays were equal. The Z flag would be set or cleared by the cmp eax, ebx
, and if it's clear at that point, control will transfer to done
-- unfortunately, immediately after that it does a couple of add
s, which will (probably) clear the Z flag again, so the sub eax, eax
is needed to set it again for the conditional jumps after the macro.
The real question would be why you need the mov eax, 0
at equal:
-- and the answer is that you don't. Along with setting the Z flag, the sub eax, eax
also sets eax to 0, which can/could be returned directly. Even if you did decide to re-load the 0 value for some reason, you probably want to use the sub eax, eax
(or xor eax, eax
) to do so (the code is a little smaller and at least on some processors, faster as well).
Edit: I should add that at least in my opinion, this is a fairly poor use of a macro. At the very least, there should be some comments to specify the macro's interface, which would probably have answered the question before it was asked.
Upvotes: 2
Reputation: 220
The result of the function is returned in the EAX register. The final sub eax, eax
is setting the value of EAX to zero before returning when the arrays match exactly.
Upvotes: 1