Understanding cmp instruction

cmp arg2, arg1 performs the same operation as sub arg2, arg1 except that none of the operands are modified. The difference is not stored anywhere.

However, the flags register is updated and can be used in a conditional jump, like jump-if-equal (JE), most often as the next instruction after the cmp.

The advantage over other instructions is that you can compare two values without destroying any of them. If you did sub arg2, arg1 and they happen to be equal, one of them would be zero afterwards. With cmp they are both still there.


I think it's very late to post an answer on this question. But I can give you a better illustration on how this CMP instruction works.

When you Compare two arguments using CMP arg1, arg2

CMP instruction sets status flags according to the comparisons between the arguments. See : wikipedia's FLAGS page

The importance of CMP applies mostly in conditional code execution (Jump - See : assembly_conditions). When the processor executes a conditional-jump jcc instruction, it checks the status flags register and jumps to the target label if it meets the conditions, otherwise falls through to the next instruction.


the results of CMP is changing the values of ZF and CF, this is some examples to understand very much CMP instruction.

Example 1: if AX < BX

MOV AX,5
MOV BX,8
CMP AX,BX 

Result : ZF and CF set to ==> "ZF = 0" and "CF = 1"



Example 2 : if AX > BX

MOV AX,8
MOV BX,5
CMP AX,BX

Result : ZF and CF set to ==> "ZF = 0" and "CF = 0"



Example 3 : if AX = BX

MOV AX,5
MOV BX,AX
CMP AX,BX 

Result : ZF and CF set to ==> "ZF = 1" and "CF = 0"



i hope you understand the results of CMP is changing the value of ZF and CF
ZF = Zero Flag
CF = Carry Flag


We use cmp arg2, arg1 when we care about whether arg1 and arg 2 are equal. The processor determines this by subtracting arg2 from arg1, then looking at the result. If the result is zero (that is, arg1 = arg2), then the processor sets the zero flag (by "sets the flag", we mean it sets it to 1). Conversely, if the result isn't zero (that is, arg1 != arg2), then the processor clears the zero flag (i.e, sets it to 0). The result itself is discarded, because we don't care what it is, only whether it's zero or not, which we now know based on whether the zero flag is set. We can then use instructions like JE, JNE, JZ and JNZ that examine the zero flag and jump (or not) based on its value. In the case of JE (jump if equal), the jump will happen if the zero flag is set, which (as we learned above) it will be if the arguments in the cmp were equal.