beqzpseudo

beqz

pseudo
RISC-V Assembly Reference

lyszt.net covers beqz and other RISC-V instructions in more detail.

Description

beqz branches when a register holds zero. The name means branch if equal to zero. With the form below, the processor jumps to the labeled position when rs is zero and otherwise continues to the next instruction.

beqz rs, label

beqz is a pseudo-instruction, a readable name that the assembler rewrites into a real instruction. It becomes the instruction below, which compares the register with zero, the special register that always holds 0.

beq rs, zero, label

beqz gives a shorter way to write the most common comparison. See beq for how branching and labels work.

Zero appears often in low-level code, which is why the shorthand exists. A zero byte marks the end of text. Zero is the usual signal that an operation succeeded. Zero also represents an empty or missing value, and countdown loops finish at zero. The zero test is used after loading a character to detect the end of a string, on a returned status to take the success path and on a counter to end a loop.

The RISC-V manual gives one reason its branches compare two registers instead of comparing one register with zero. Comparisons against zero need a non-trivial circuit delay, so they are almost as expensive as arithmetic magnitude comparisons. beqz is therefore a pseudo-instruction that uses beq with zero.

The first line below reads more clearly than the second, which spells out the comparison with zero.

beqz t0, done
beq t0, zero, done

Pseudo-instructions exist for readability, and the machine code they produce is identical. Its opposite is bnez, which branches when a value is not zero.

Expands to

beq rs, zero, label

The assembler replaces this pseudo-instruction with the real instruction or instructions listed above.

Example

li t0, 0
beqz t0, done   # t0 == 0, so jump to 'done'