← again tap: answer good → ↑ swipe up at the end: next
Question
How do arithmetic instructions affect the flags register?
Answer
Most arithmetic and logical instructions set the condition flags as a side effect — but lea and mov set nothing, and inc/dec notably leave the carry flag alone.
Knowing which instructions touch flags is essential when reading code, because a conditional jump depends on whatever last set them.
| Instruction | Flags modified |
|---|---|
| add, sub, cmp | ZF, SF, CF, OF |
| and, or, xor, test | ZF, SF (CF and OF cleared to 0) |
| inc, dec | ZF, SF, OF (CF unchanged!) |
| lea, mov | none |
After cmp a, b (which computes b − a):
| Condition | Unsigned test | Signed test |
|---|---|---|
| b == a | ZF=1 | ZF=1 |
| b < a | CF=1 | SF≠OF |
| b > a | CF=0 and ZF=0 | SF=OF and ZF=0 |
add %rbx, %rax # sets all four flags
jo overflow # OF=1 → signed overflow
jc carry # CF=1 → unsigned overflow
jz zero # ZF=1 → result was zero
Gotcha: because inc/dec don't touch CF, multi-word ("bignum") arithmetic that relies on carry must use add $1 / sub $1 instead.
Go deeper:
FLAGS register (Wikipedia) — the ZF/SF/CF/OF condition flags set by arithmetic.
Felix Cloutier — ADD — concrete per-instruction flag effects for ADD.
Question
What does the test instruction do and when is it used?
Answer
test computes a bitwise AND of its operands and sets the flags, but throws the result away — it's and without the side effect of changing the destination.
test is the idiomatic way to ask yes/no questions about a value without disturbing it. Three classic uses:
1. Is a register zero? ANDing a value with itself is zero only if the value is zero:
test %rax, %rax
jz is_zero
2. Is a particular bit set? AND with a mask:
test $1, %al # bit 0 — is the number odd?
jnz is_odd
test $0x80, %al # bit 7 — the sign bit
jnz is_negative
3. Is a pointer NULL?
test %rdi, %rdi
jz handle_null
Why test %rax,%rax instead of cmp $0,%rax? It produces a shorter encoding (no immediate to store) and is the conventional zero-check, so compilers emit it constantly — recognizing it is essential when reading disassembly.
Go deeper:
Felix Cloutier — TEST — the bitwise-AND-that-sets-flags-and-discards-result semantics.