Assembly & the CPU

the flags / status register

When you subtract two numbers, you often care about the side facts as much as the answer: was the result zero? Did it go negative? Did the number wrap past the largest it could hold? The flags register is where the CPU records exactly these side facts. It is a special register whose individual bits — the flags — each report something about the most recent arithmetic or comparison.

A few flags matter constantly. The zero flag is set when the last result was exactly zero. The sign flag copies the sign bit of the result (set when negative, viewed as two's complement). The carry flag catches an unsigned overflow — a carry or borrow out of the top bit. The overflow flag catches a signed overflow. Crucially, the way a program asks a question like 'is a equal to b' is to compute a - b with a cmp instruction, which sets these flags but throws the result away, and then run a conditional branch that looks only at the flags. A je (jump if equal) branches when the zero flag is set; jl, jg, jne and friends each test a particular combination of flags.

This two-step dance — set the flags, then branch on them — is how every if, while, and for condition compiles down. It also explains why signed and unsigned comparisons use different branch instructions: they consult different flags (jl/jg for signed via sign and overflow flags; jb/ja for unsigned via the carry flag). Getting this pairing wrong is a classic source of bugs when reading or writing assembly by hand.

cmp eax, ebx computes eax - ebx only to set the flags; the following je target branches there exactly when eax == ebx (the zero flag is set).

Compare sets the flags and discards the result; the conditional branch reads only the flags.

The flags reflect only the most recent flag-setting instruction; an unrelated instruction in between can change them, so a cmp must sit immediately before the branch that depends on it. Not every instruction updates the flags — for example a plain mov leaves them untouched.

Also called
status registercondition flagsEFLAGSRFLAGS狀態暫存器條件旗標