views:

173

answers:

3

(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?

+4  A: 

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.

Michael Burr
so the above is used on conjunction with 'jne'. does 'jne' look at the ZF?
hatorade
Yes - jne (jump not equal) is checking the zero flag conditionally for a jump.
Michael Dorgan
Yes - `jne` will jump if `ZF` is not set (`jne` is equivalent to `jnz` - as in they are the same opcode).
Michael Burr
+1  A: 

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

Michael Dorgan
Bah, too slow on the draw...
Michael Dorgan
A: 

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.

Ira Baxter