1

I'm new to assembly language and I've made a simple program which adds two arrays of int(described in data segment as word) and prints and saves it to the third variable. I've used outdec(a procedure) to print the sum(it requires value to be in ax to print). My question is that I've 8 elements in both of my arrays and in order to access each elements, value of cx should be 8 because my loop is repeating 8 times to get each of the two elements. but if i use cx, 8 so my programs only prints sum of 4 elements unless i put cx, 16. When i checked the value of cx at each iteration I found out that cx is decrementing 2 i-e 16,14,12,10 but how's that possible? when i use byte instead of word datatype then cx is working normally. my question is that, is somehow cx related to the datatype? because according to me no matter what datatype I'm using for my variables cx should decrement by 1.

.model small
.stack 100h
.data
arr1 dw 21,32,65,76,56,-11,10,-34
arr2 dw 0,11,-3,90,43,56,66,9
outp dw lengthof arr1 dup(?)

.code
main proc
mov ax, @data
mov ds, ax
mov cx, 16
mov si, 0
traverse:
mov ax,  word ptr arr1[si]
add ax, word ptr arr2[si]
mov outp[si], ax
call outdec
mov ah, 2
mov dl, ','
int 21h
dec cx
add si, 2
loop traverse

mov ah, 4ch
int 21h 

main endp

outdec proc
push ax
push bx
push cx
push dx
mov bx,10
mov cx,0
cmp ax,0
jge @else
push ax
mov ah,2
mov dl,'-'
int 21h
pop ax
neg ax
@else:
mov bx,10
mov dx,0
div bx
push dx
inc cx
cmp ax,0
jnz @else
print_label:
pop dx
mov ah,2
add dl,48
int 21h
loop print_label
pop dx
pop cx
pop bx
pop ax
RET
outdec endp
end main
Michael Petch
  • 46,082
  • 8
  • 107
  • 198
Moheb
  • 138
  • 1
  • 6
  • 6
    the `dec cx` instruction subtracts one from _CX_, and the `loop` instruction itself subtracts 1 from _CX_ .So you end up subtracting 2 on each iteration. – Michael Petch Apr 26 '17 at 15:56
  • 1
    oh my god, my god such a stupid mistake. Thanks for your answer. It was awkward sorry and thanks. – Moheb Apr 26 '17 at 15:59
  • Possible duplicate of [Assembler - loop with ECX](http://stackoverflow.com/questions/9830125/assembler-loop-with-ecx) – Cody Gray - on strike Apr 27 '17 at 08:01
  • The `LOOP` instruction is equivalent to `DEC cx` + `JNZ ...`. On the 8086, it is approximately 2 cycles faster than the separate pair of instructions, but on the 386 and everything afterwards (including all modern processors), `LOOP` is *slower* than `DEC`+`JNZ` and should be avoided. It buys you very little on the 8086, too, so there's a good argument for forgetting about it entirely. – Cody Gray - on strike Apr 27 '17 at 08:03
  • ok thanks for this information. – Moheb Apr 29 '17 at 21:44

0 Answers0