REPE and REPZ are two names for the F3h prefix, the same byte as REP. In front of CMPS or SCAS it adds a second exit: after each compare, CX is decreased and the loop also stops if ZF = 0. So it runs while CX is not 0 and the elements keep matching.
| Ends because | ZF | CX |
|---|---|---|
| a difference was found | 0 | elements not yet compared (may be 0) |
| all CX elements were equal | 1 | 0 |
| CX was 0 at the start | unchanged | 0 |
Decide with JE / JNE right after it. Testing CX alone is a classic bug: a difference in the last element also ends with CX = 0. And if CX can start at 0, check that first (JCXZ), since then no compare runs and ZF is left over from earlier code.
Finding where
After a difference SI and DI have already stepped past the differing elements. Going forward over bytes, the index of the first difference is SI - start - 1; the number of elements that matched is the same number. For words it is (SI - start - 2) / 2.
CLDMOV SI, OFFSET STR1MOV DI, OFFSET STR2MOV CX, 6REPE CMPSBJE SAME1 ; no difference at allMOV AX, SISUB AX, OFFSET STR1DEC AX ; index of the first difference: 3ADD AL, '0' ; digit -> characterMOV DL, ALMOV AH, 02h ; DOS: print DLINT 21hJMP DONE1SAME1:MOV DL, '='MOV AH, 02hINT 21hDONE1:STR1 DB 'hello!'STR2 DB 'help!!'
With SCAS, REPE skips over elements equal to AL: MOV AL, ' ' / REPE SCASB steps over leading spaces, and the first other character is at DI - 1. In front of MOVS, STOS or LODS the prefix ignores ZF and acts as plain REP.