Discussion:
What's the difference between TEST and CMP ?
(too old to reply)
sugaray
2004-02-27 23:00:05 UTC
Permalink
Hi, I'm a rookie in assembly language, this
question just came up my mind, so I post it
here in the hope that someone would explain
more details about the topic.

when test to see if a variable contains
a zero value, people ususally use

TEST reg,reg
JZ Lable1

alternatively,

CMP reg,0
JE Label1

is also correct,
So, what's the difference ?
and any other important things which pertinent
is also welcome here. thanx in advance :))))
Matt Taylor
2004-02-28 01:59:17 UTC
Permalink
Post by sugaray
Hi, I'm a rookie in assembly language, this
question just came up my mind, so I post it
here in the hope that someone would explain
more details about the topic.
when test to see if a variable contains
a zero value, people ususally use
TEST reg,reg
JZ Lable1
alternatively,
CMP reg,0
JE Label1
is also correct,
So, what's the difference ?
and any other important things which pertinent
is also welcome here. thanx in advance :))))
The test and cmp instructions are aliases for and and sub respectively
except that test and cmp only update the flags. Therefore:

test eax, eax ; sets flags like and eax, eax
jz @eax_is_zero

cmp eax, 0 ; sets flags like sub eax, 0
je @eax_is_zero

Note that je and jz are aliases for each other. It is true that x - x == 0,
so if you cmp eax, eax (sub eax, eax), then the result will be 0 and the
machine will set ZF (zero flag) to 1.

Here's an example that shows how these 2 instructions differ:

test eax, 1
jnz @eax_is_odd
jc @never_branch
jo @never_branch

cmp eax, 1
jnz @eax_is_not_one
jc @eax_is_zero
jo @eax_is_int_min

Here test is only checking the least significant bit, so if eax == 0 then
the jnz will not be taken. If eax == 1 then the jnz will be taken. Both CF
(carry flag) and OF (signed overflow flag) are cleared to 0 by test, so a
jc/jo after a test will never branch.

The cmp works a bit differently as you can see. eax - 1 == 0 only if eax ==
1, so jnz is taken if eax != 1. The only case where sub eax, 1 will
underflow is when eax == 0, so if CF is set then we know eax was 0. Also, OF
will be set if eax == -2^31 since eax will wrap around to 2^31 - 1.

-Matt
Jonathan Bartlett
2004-02-28 05:57:15 UTC
Permalink
Basically, TEST and CMP are both mathematical operations which simply
throw away the answer, and only use the flag settings.

TEST does a logical "and" of the two arguments, and sets the flags
accordingly (but throws away the answer afterwards)

CMP does a subtraction of the two arguments, and sets the flags
accordingly (but throws away the answer afterwards). The

The jumps are based entirely off of the flag settings.

Jon

-------
Buy my assembly language book -
http://www.cafeshops.com/bartlettpublish.8640017

Loading...