Question

I'm reading some code that does the following:

OR al, al
JNZ loc_123456

If I am reading this correctly, the OR command just sets a flag bit, which is then tested that the register doesn't have any nonzero values.

Why would you write it that way, and not

CMP al, 0
JNE loc_123456

which is much more readable? I assume the hardware is doing something similar in each case...

Was it helpful?

Solution

As you state, the execution of the OR operation sets the status flags, which you test with the following JNZ (Jump if Not Zero) conditional branch.

The OR opcode on many processors with implicit register addressing (though not on the x86) can be encoded into a single opcode.

Using CMP al, 0 takes the opcode plus uses additional memory for the immediate parameter. So it is basically just to save a little memory and possibly gain a bit of speed.

Those were common practices in early assembly language development when memory was scarce. But the practices have carried through to even today.

OTHER TIPS

Using or x, x to test for zero is a common idiom, so it's perfectly readable.

You should prefer test x, x (also a common idiom) though, it macro-fuses with the branch on many processors.

Avoid cmp reg, 0. Having a lot of memory is no reason to waste it, and there's nothing to gain here. Even if there was a readability difference - this is assembly, readability is not the point. And cache space and instruction fetch bandwidth are still limited resources.

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