Skip to content
systemcoding.dev
Assembly

Test a register for zero with test rax, rax

Test a register for zero with test rax, rax: a 3-byte instruction that sets ZF and SF without the 4-byte immediate cmp needs. NASM 2.16, x86-64.

1 min read
Summarize in AI

When you only need to know whether a register is zero or negative, test reg, reg is the short form. It ANDs the register with itself, throws the result away and sets the flags: ZF when the value is zero, SF from the top bit, CF and OF cleared. cmp rdi, 0 answers the same zero question but needs an immediate byte, so it is one byte longer.

is_null.asmasm
bits 64
global is_null
is_null:                ; int is_null(void *p)
    test rdi, rdi       ; 48 85 FF
    sete al
    movzx eax, al
    ret
Text
00000000  4885FF            test rdi,rdi
00000003  0F94C0            setz al
00000006  0FB6C0            movzx eax,al
00000009  C3                ret

cmp rdi, 0 assembles to 48 83 FF 00, four bytes against three. The two set ZF identically, but test always clears CF and OF, whereas cmp rdi, 0 also yields CF=0 and OF=0 here, so the difference is purely size. Use test for zero and sign checks, and keep cmp for comparing against a non-zero value. The encodings come from the Intel SDM, and the System V ABI passes the pointer in rdi.

Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.