# When to use TEST vs CMP in Assembly Code?

• 10-27-2012
Genxi
When to use TEST vs CMP in Assembly Code?
Hi there,

I'm sorry if this question doesn't belong here, this may be deleted if that is the case.

Anyways, I am curious when TEST and CMP are used in assembly codes? According to examples in my textbook, it seems like they could be used interchangeably...but then again, why would they have them be separate instructions if so?

Thank you for taking the time to read my question (and to answer)!

--Genxi
• 10-27-2012
Nominal Animal
On x86, test does a binary AND between the operands, just does not save the result anywhere. cmp subtracts the second operand from the first without actually modifying the first operand.

In other words, if you wanted to check if bit 6 (01000000b = 26 = 64) is set in register ch, then you'd use test ch, 64. If you wanted to see if ch is less than/equal to/greater than 64, then you'd do cmp ch, 64.
• 10-27-2012
Genxi
Quote:

Originally Posted by Nominal Animal
On x86, test does a binary AND between the operands, just does not save the result anywhere. cmp subtracts the second operand from the first without actually modifying the first operand.

In other words, if you wanted to check if bit 6 (01000000b = 26 = 64) is set in register ch, then you'd use test ch, 64. If you wanted to see if ch is less than/equal to/greater than 64, then you'd do cmp ch, 64.

Ah, that makes sense. Is it possible to use "cmp ch,64" instead of "test ch, 64" to test equality since you know that if ch and 64 are equal, their difference is simply 0.

In another words, are the follow codes the same?:

Code:

```cmp ch,64 je .L7```
Code:

```test ch,64 je .L7```

Thank-you again!
• 10-27-2012
Nominal Animal
Quote:

Originally Posted by Genxi
Ah, that makes sense. Is it possible to use "cmp ch,64" instead of "test ch, 64" to test equality

No. The former compares for equality, and the latter just tests bit 6 (26=64). test only considers the bits that are set in the second operand, it ignores all the other bits.

Remember, the difference is that cmp does a subtraction, and test a binary AND operation, with the result discarded and only the flags affected. They are two very different operations.