6

I am trying to figure out the behavior of conditional jumps (JE/JNE, JZ/JNZ) in the x86 instruction set familly.

Which condition flags CMP instruction sets and how, if the result is equal and if it is not? For example:

  • CMP eax, 0 (true)

  • CMP eax, 0 (false)

perror
  • 19,083
  • 29
  • 87
  • 150
PaHa
  • 145
  • 1
  • 3
  • 7

2 Answers2

9

Furthermore, with the CMP instruction, the destination operand doesn't change. Just the flags.

Let me illustrate. Let's say EAX = 00000005 and EBX = 00000005. If we do this arithmetic operation:

CMP EAX, EBX

What's happening, is in effect this:

EAX - EBX ----> 00000005 - 00000005

Since the result would be 0, but we don't change the destination operand in a CMP instruction, the zero flag is set to 1 (since it's true).

So, as we saw, depending on the result of the previous arithmetic operation, flags can be set accordingly:

enter image description here

she_roar
  • 106
  • 5
  • Presumably, where values are signed and of opposite signs (because the CPU doesn't have a way to distinguish signed from unsigned) that use of the C flag isn't true - so 0xff > 0x01 makes it also look like -1 > 1. I expect in that case you'd check the S flag which is true if the result would be negative. – Jim Driscoll Feb 17 '24 at 11:30
4

The CMP instruction does internally a SUB and sets the flags accordingly.

So all flags that are set by a SUB are also set by CMP.

Namely the flags SF, ZF, AF, PF, and CF are set.

This information is taken from the Intel manual for the processors (https://software.intel.com/en-us/articles/intel-sdm).

Uwe Plonus
  • 343
  • 2
  • 8