DAY 10
1
Software Development

[Day10] 循環指令 - loop

loop

``````p:
;循環內容
loop p
``````

loop 會搭配 `cx 暫存器` 一起使用，執行到 loop 時會先將 cx 遞減一，接著判斷 cx 的值，如果不為零則跳到標號地址繼續執行，如果為零則退出循環，有點像 C 語言的 `do while` 語句。

``````int cx = 10;
do {
//循環內容
} while(cx > 0)
``````

``````assume cs:code
code segment
start:
mov ax, 2

mov ax, 4c00h
int 21h
code ends
end start
``````

``````assume cs:code
code segment
start:
mov ax, 2
mov cx, 999   ; 2 x 1000

loop p

mov ax, 4c00h
int 21h
code ends
end start
``````

loop + [ ]

``````mov ax, 1
mov ds:[0], ax   ; [0]=1
inc ax
mov ds:[1], ax   ; [1]=2
...
``````

``````assume cs:code
code segment
start:
mov bx, 0100h
mov ds, bx

mov bx, 0      ; 偏移地址從0開始
mov ax, 1      ; 數值從1開始
mov cx, 10     ; 迴圈次數10

p:  mov [bx], ax   ; 將 ax 的值放入記憶體 [bx] 中
inc bx         ; 遞增 bx
inc ax         ; 遞增 ax
loop p

mov ax, 4c00h
int 21h
code ends
end start
``````

段前綴

``````mov ds:[0], ax
...
mov [bx], ax
``````

``````assume cs:code
code segment
start:
mov ax, ds:[0]
mov ax, ds:[bx]
mov ax, es:[0]
mov ax, es:[bx]
mov ax, ss:[0]
mov ax, ss:[bx]

mov ax, 4c00h
int 21h
code ends
end start

``````