Search code examples
assemblycmp

Why take CMP ECX, ECX?


I am looking through some assembly and I see the line

CMP ECX, ECX

Which doesn't make sense to me, because isn't it always true A==A? (Reflexive property)

Not sure if this will help, but it is used in this context:

CPU Disasm
Address   Hex dump          Command                                         Comments
00414A24  |.  39C9          CMP ECX,ECX
00414A26  |.  F3:A6         REPE CMPS BYTE PTR DS:[ESI],BYTE PTR ES:[EDI]
00414A28  |.  0F92C0        SETB AL
00414A2B  |.  0F97C2        SETA DL
00414A2E  |.  28C2          SUB DL,AL
00414A30  |.  0FBEC2        MOVSX EAX,DL

Solution

  • If the ECX register is zero then the repe cmpsb is not executed at all. This means that the following setb and seta instructions would produce garbage!

    Thus the programmer chose to make sure the flags have a defined state. In this case cmp ecx,ecx results in a CarryFlag=0 and a ZeroFlag=1. setb will make AL zero and seta will make DL zero.

    @user35443 repe cmpsb does not decrement ECX beforehand. Repeats do check if ECX is zero but otherwise will post-decrement.

    @Hans Passant repe cmpsb does not need you to initialize the Z-flag nor any other flag except the direction flag.