Search code examples
loopsassemblycpu-wordinfinitetasm

Infinite loop when I tried to make a word counter


I was trying to make a word counter (counts how many words there are in the string) and I used the jmp instruction to go back to the WORDCOUNT label, but the problem is that it keeps making an infinite loop. When I add jmp WORDCOUNT before the ADDCOUNTER, it makes an infinite loop. What could be the cause of this? I would really appreciate it if someone can explain it to me. :)

; count the number of words in the string
        mov ax, 0000 
        mov bx, 0000 ; will contain the data
        mov cx, 0000 ; will count the number of words
        mov dx, 0000 ; erase all content to 0000
        lea bx, USERSTRING ; bx will contain the user string input
WORDCOUNT:
        mov al, [bx] ; al will contain bx data inside
        cmp al, "$" ; check if it is the end of the string already
        je ENDWORDCOUNT ; get out of the loop if done
        cmp al, " " ; if the value has space 20h
        je ADDCOUNTER ; then go to ADDCOUNTER to add
        inc bx ; hop to the next address one at a time
        jmp WORDCOUNT
    ADDCOUNTER:
            inc cx ; add cx with 1 because it means there is space
            jmp WORDCOUNT

ENDWORDCOUNT:
        call TODECIMAL
        mov cx, ax ; ax transfers the decimal version here
        mov word ptr HOWMANYWORDS, cx ; this one will be turned into a decimal dude help me here huhuhu
        lea dx, HOWMANYWORDS
        call PRINTF

Solution

  • When you find a space character you jump to ADDCOUNTER, where you increase cx but not bx, so upon jumping back to WORDCOUNT you'll be reading the same character again (i.e. the space), and so on, for all eternity.
    You'll need to have an inc bx in the ADDCOUNTER case as well.