Question

(ia32) for example,

test $eax, $eax

why would you ever want to do that? it does $eax & $eax, right? shouldn't this always set the flag register to say that they are equal..?

addendum: so test will set the ZF (as mentioned below) if the register is zero. so is test (as used above) mainly just used to tell if a register is empty? and ZF is set if so?

Was it helpful?

Solution

It'll set ZF (the zero flag) if the register is zero. That's probably what it's most commonly used to test. It'll also set other flags appropriately, but there's probably far less use for those.

Also, I should mention that test doesn't really perform a comparison - it performs a bitwise and operation (throwing away the result, except for the flags).

To perform a comparison of the operands, the cmp instruction would be used, which performs a sub operation, throwing away the results except for the flags. You are correct that a

cmp $eax, $eax

would not have much point, as the flags would be set according to a zero result every time.

OTHER TIPS

This is setting the zero flag, the same way that using or $eax,$eax can non-destructively test for the zero flag as well.

It sets the Z and S flags on the processor, so you can tell after "test eax,eax" (or any other register 8, 16, 32 and I think 64 bits) if the value is zero, or if the sign bit is set, by using "je/jne/jz/jnz" or "js/jns" respectively. In 30 years of coding for x80/x86 architectures, I've done this a huge number of times, with most of the register combinations. (You don't use this in practice on ESP!)

IIRC, there's a parity bit that's calculated too, so by do this test you can tell if the number of bits set in the register is even or odd, using "jp/jnp". I've never had a use for this.

This instruction is not meant to check only if the value of %eax is zero. It can be as a whole used to check if the value %eax is zero or positive or negative. The biggest advantage of using it this way is it doesn't modify the vale of %eax (after performing %eax & %eax, it just discards away the value) and sets the condition flags as follows.

if %eax value is zero, OF, CF, ZF = 0 (set to zero)
else SF = MSB of the result (here, result is %eax & %eax). So if the number is negative, we get SF = 1, otherwise SF = 0.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top