ASSEMBLY / CHAPTER 08

Comparisons and signed branches

Master

Choose branch conditions that match the meaning of the compared values.

By the end of this chapter

  • Explain cmp without changing operands
  • Distinguish signed and unsigned comparisons
  • Keep flag-producing and flag-consuming operations aligned

The idea

Enter with signed two’s complement and arithmetic flags understood. cmp computes flags as if it subtracted the second operand from the first, without storing the subtraction result. A later conditional jump interprets those flags. Equality uses the zero flag, while signed and unsigned order comparisons require different flag relationships. The operand bits alone do not select the correct interpretation.

Use jl for signed less-than and jb for unsigned below. These can disagree when the high bit is set. Instructions between cmp and the branch may overwrite the flags, so keep the intended producer and consumer connected. In a trace, first identify operand width and numeric interpretation, then select the branch. Do not translate every less-than symbol into the same machine instruction.

Assembly example
mov eax, -2
cmp eax, 1
jl .less
mov edx, 0
jmp .done
.less:
mov edx, 1
.done:
Result
Final EDX = 1; no console output.

Interpreted as a signed thirty-two-bit value, negative two is less than one, so JL takes the branch.

Try it yourself

Write two traces comparing 0xFFFFFFFF with 1, one using signed ordering and one unsigned ordering.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Which branch tests unsigned EAX < EBX immediately after cmp eax, ebx?