Search code examples
assemblyx86conditional-statementseflags

Explain how the flags work in conditional jumps in Assembly language


I'm new to Assembly language, I'm reading Assembly Language Programming By Ytha Yu, Charles Marut

Anyway, I'm in Chapter 6 and I can't figure out the case of the flags which the processor uses to do conditional jumps. I know what the flags basically do, for example, I know that Overflow flag sets or resets if any overflow occurs or doesn't in the last instruction. But I can't figure out how they play into the conditions of the jumps.

Signed Conditional Jumps Unsigned Conditional Jumps

It would be really helpful if anyone helped me understand the uses of flag registers to implement conditional jumps.


Solution

  • The general idea is: there are some operations that set or clear individual flags - arithmetic, bitwise, comparisons. You are then free to perform conditional jumps based on the result of those operations.

    Let's consider the most basic case - jump if one variable is greater than another. Assuming the variables are in the general purpose registers, and the code is 32-bit, this would go:

    cmp eax, ebx
    ja AOverB
    

    Now, what does that do? The CMP line calculates the value EAX-EBX, doesn't store it anywhere, but sets the flags. Specifically, the Zero flag is set if the result of the subtraction is zero (i. e. EAX-EBX=0, i. e. EAX=EBX), and cleared if it's not. The Carry flag is set if EAX<EBX (i. e. subtracting them would require a borrow). So the JA command goes: take the jump if the Zero flag is not set and the Carry flag is not set either (that is, neither EAX=EBX nor EAX<EBX). By obvious math, if neither of those flags is set, that means EAX>EBX.

    Did that help? Do you get the concepts of carry and borrow, and their close relative overflow?