# CMP Directive Nature
cmp是比较指令,cmp的功能相当于减法。
Format
cmp 操作对象1,操作对象2
Function
计算操作对象1-操作对象2,但并不保存结果,可以根据flag标志寄存器来判断结果。
Positive judgment
如果(ax) = (bx) 则(ax)-(bx) = 0,所以:zf=1。如果(ax) != (bx) 则(ax)-(bx) != 0,所以:zf=0。如果(ax) < (bx) 则(ax)-(bx)将产生借位,所以:cf=1。如果(ax) >=(bx) 则(ax)-(bx)不产生借位,所以:cf=0。如果(ax) > (bx) 则(ax)-(bx) != 0,也不产生借位,所以:zf=cf=0。如果(ax) <=(bx) 则(ax)-(bx)可能为0,也可能产生借位,所以:zf=1或zf=1。(1、3起码满足一个)
Reverse Judgment
指令cmp ax,bx 的逻辑含义是比较ax和bx的值,如果执行后:1. zf=1 ===> (ax)=(bx)2. zf=0 ===> (ax)!=(bx)3. cf=1 ===> (ax)<(bx)4. cf=0 ===> (ax)>=(bx)5. cf=zf=0 ===> (ax)>(bx)6. cf=1或zf=1 ===> (ax)<=(bx)
How to remember?
1. zf是0标志寄存器,zf=1时,ax=bx;zf=0时,ax != bx。2. cf是进位借位标志寄存器,cf=1时,ax<bx;cf=0时,ax>=bx。3. 根据1、2组合可以推出另外两个。
How does CMP instructions work?
The comparison results of CMP directives need to be detected by conditional transfer directives.
| instruction | explanation | meaning | Related flag bits for detection |
|-------|-------|-------|----------------|
|je|e:equal| equals the transfer |zf=1|
|jne|ne:not equal| is not equal to the transfer |zf=0|
|jb|b:below| Lower then transfer |cf=1|
|jnb|nb:not below| No less than then transfer | cf=0|
|ja |a:above| Higher then transfer | Cf=0 and zf=0|
|jna| Na:not above| No higher then transfer | Cf=1 or zf=1|
"Assembly Language (third edition)" CMP directive