Flags and the status register
The flags register
The flags register (EFLAGS or RFLAGS) holds one-bit status flags. CMP and arithmetic update them, and conditional jumps read them. You rarely read the register itself.
cmp rax, rbx ; sets flags, changes nothing else
The common flags
ZF (zero flag) sets when a result is zero. CF (carry flag) sets when an unsigned operation overflows. SF (sign flag) copies the result sign bit. OF (overflow flag) sets on signed overflow.
mov rax, 5 sub rax, 5 ; result 0: ZF = 1 cmp rax, rbx ; like sub, but discards the result
Which instructions set them
CMP, SUB, ADD, INC, DEC, AND, OR, XOR, and TEST update flags. MOV does not: it moves data without touching status. TEST is CMP without subtraction: it ANDs its operands, discards the result, and sets SF, ZF and PF while clearing CF and OF.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which flag is set when the result of an operation is zero?
Answer
ZF
ZF, the zero flag, is set when the result is zero and cleared otherwise.
-
Which flag records an unsigned overflow?
Answer
CF
CF, the carry flag, is the unsigned overflow bit; OF is the signed one.
-
What does CMP do with its operands?
Answer
It subtracts them and discards the result
CMP is a subtraction whose only result is the flags.
-
Which instruction does not change the flags?
Answer
MOV
MOV only copies bits; the arithmetic and logic instructions set the flags.
-
What does TEST set when both operands have no common 1 bit?
Answer
ZF, because the result is zero
TEST ANDs the operands, and a zero result sets the zero flag.
-
Which flag copies the sign bit of the result?
Answer
SF
SF is the sign flag, the top bit of the result.
-
What does this program print?
default rel section .data eqmsg db "eq", 10 nem db "ne", 10 section .text global _start _start: mov rax, 5 cmp rax, 5 je equal mov rsi, nem jmp print equal: mov rsi, eqmsg print: mov rax, 1 mov rdi, 1 mov rdx, 3 syscall mov rax, 60 xor rdi, rdi syscallAnswer
eq
CMP of equal values sets ZF, so the je branch loads the eq message.
-
What does
cmp rax, rbxchange?Answer
Only the flags
CMP computes rax - rbx for the flags and writes neither register.
-
What does this program print?
default rel section .data yes db "yes", 10 no db "no", 10 section .text global _start _start: mov eax, 0 test eax, eax jz zero mov rsi, no jmp print zero: mov rsi, yes print: mov rax, 1 mov rdi, 1 mov rdx, 4 syscall mov rax, 60 xor rdi, rdi syscallAnswer
yes
TEST of zero with itself gives zero and sets ZF, so jz takes the yes branch.
-
Which flag pair would you read after comparing signed values?
Answer
SF and OF
Signed comparisons use SF and OF; unsigned ones use CF.
The snippets on this page are fragments, not whole programs: they show the flags and the instructions that set them. They were assembled with NASM 3.01 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev