Home > Software engineering >  Why do i add #4 to a regsiter to have the next iteration?
Why do i add #4 to a regsiter to have the next iteration?

Time:07-04

in school we are learning assembly. I tried to study this code

RES:       .word 0
N:         .word 5
NUM1:      .word 3, -17, 27, -12, 322

LDR r1, N
ADR r2, NUM1
MOV r0, #0

LOOP:      LDR r3, [r2]
           ADD r0, r0, r3
           ADD r2, r2, #4
           SUB r1, r1, #1
           CMP r1, #0
           BGT LOOP
           STR r0, RES

But i dont understand this line ADD r2, r2, #4 our teacher tell us this is for next iteration, but why it is not ADD r2, r2, #1 ?

CodePudding user response:

ARM systems, like most today, are byte addressable.  A 32-bit integer stored in memory occupies 4 bytes.  Each of those 4 bytes has its own byte address.  Thus, in an array of integers, the first integer is at NUM1 and the second is at NUM1 4.  We refer to multi-byte items by just one address — the lowest one among them.  This applies both to 4 byte integers as well as the entire array: we refer to the whole array by its lowest address.

Adding only #1 would be a logic error, as that would not reach the next integer in the array.  If the array had byte or char elements that would be appropriate.

An array holds items of like type, so the scaling necessary for A[i] is that i is multiplied by the element size, for 4 byte integers, that is 4.

In a structure holding not necessarily like members, we add up the size in bytes of the prior members, plus any alignment padding between elements, to reach the offset of a given structure member.

  • Related