Assembly Language for Beginners

(Jeff_L) #1

1.17 More about strings.


Usually the condition is checkedbeforeloop body, but the compiler may rearrange it in a way that the
condition is checkedafterloop body.


This is done when the compiler is sure that the condition is alwaystrueon the first iteration, so the body
of the loop is to be executed at least once:


Listing 1.180: x86
MOV REG, 2 ; initialization
body:
; loop body
; do something here
; use counter in REG, but do not modify it!
INC REG ; increment
CMP REG, 10
JL body


Using theLOOPinstruction. This is rare, compilers are not using it. When you see it, it’s a sign that this
piece of code is hand-written:


Listing 1.181: x86
; count from 10 to 1
MOV ECX, 10
body:
; loop body
; do something here
; use counter in ECX, but do not modify it!
LOOP body


ARM.


TheR4register is dedicated to counter variable in this example:


Listing 1.182: ARM
MOV R4, 2 ; initialization
B check
body:
; loop body
; do something here
; use counter in R4, but do not modify it!
ADD R4,R4, #1 ; increment
check:
CMP R4, #10
BLT body


1.16.5 Exercises.



1.17 More about strings


1.17.1 strlen()


Let’s talk about loops one more time. Often, thestrlen()function^103 is implemented using awhile()
statement. Here is how it is done in the MSVC standard libraries:


(^103) counting the characters in a string in the C language

Free download pdf