Bogdan M.
Bogdan M.

Reputation: 2181

Assembly 80x86 Loop should not loop for ever?

I have the following code:

assume cs: code, ds:data
code segment
start:
    mov ax,data
    mov ds, ax

    xor cx,cx
    repeta:
        inc cx
        xor cx,0
        loop repeta

    mov ax, 4Ch
    int 21h

code ends  
end start 

By my knowledge it should loop for ever or until error, but actually it does not. Why?

How I imagine that it works:

xor cx,cx - cx = 0

enters: repeta code segment

 inc cx  - cx = 1

does nothing

xor cx,0 - cx is still 1

Verify if cx is different from 0, if true jump to label repeta

loop repeta

In reality it does not repeat, why?

Upvotes: 0

Views: 83

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409136

According to this, the loop instruction decreases ECX and jumps unless ECX is zero.

And if ECX is 1 before the loop instruction, then the loop instruction will decrement it to zero and not jump.

Upvotes: 1

Guffa
Guffa

Reputation: 700152

The loop will end after the first iteration, because the loop instruction will decrease cx to zero, then check if it is non-zero.

Ref: http://web.itu.edu.tr/kesgin/mul06/intel/instr/loop.html

"Decrements CX by 1 and transfers control to label if CX is not Zero."

Upvotes: 3

Related Questions