简体   繁体   中英

C while loop in assembly

    //R0=cells R1=numb R2=value

    count = 0 ;
    while (numb-- != 0)
    {
        if (cells[numb] == value) count++ ;
    }
    
    return count;
}

What I did in assembly:

Count:          // R0 = cells, R1 = numb, R2 = value
    PUSH {R4}
    MOV  R4,0
    LDR  R0,[R1]
    CMP  R0,R2
    ADD  R4,R4,1
    POP  {R4}
    BX   LR
.end

I know this is incorrect but am unsure of where to work. I don't want a complicated assembly code.

Do you really need to loop over the array backwards with a decrement? It will be easier for you to do it forwards with an increment.

You have made quite a few mistakes:

To return a value you have to leave it in r0. You leave your result in r4, but then you pop {r4} so you have overwritten your answer.

You have correctly compared r0 with r2, but then you increment r4 regardless of the result if the comparison. You need to change add to addeq (add if equal). If you are in thumb state you need to preceed the addeq with "it eq" (if-then equal).

After that you need to do something similar with another register that holds the loop control variable. Then you can do beq or bne (branch if equal, branch if not equal) based on the result of the comparison.

A good way to learn is to write the whole function in c and then compile with the -S flag to get assembler output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM