# introductory example; finds the sum of the elements of an array # assembly/linking Instructions: # as -a --gstabs -o add4.o Add4.s # ld -o add4 add4.o .data # start of data segment x: .long 1 .long 5 .long 2 .long 18 sum: .long 0 .text # start of code segment .globl _start _start: movl $4, %eax # EAX will serve as a counter for # the number words left to be summed movl $0, %ebx # EBX will store the sum movl $0, %ecx # ECX will serve as an offset, relative to x, of the # current element to be summed top: addl x(%ecx), %ebx # see comment at end below addl $4, %ecx # move pointer to next element decl %eax # decrement counter jnz top # if counter not 0, then loop again done: movl %ebx, sum # done, store result in "sum" # The add instruction in the line labeled "top" uses "indexed" addressing # mode, in which an operand is specified as being a register-number of # bytes past a constant base. Here, x(%ecx) means "ECX bytes past x." So # for example to look at the third element of x, ECX must contain 8. # # Any constant can be used as the base. For example, (x+4)(%ecx) would # refer to the word ECX bytes past x+4 (or, if you prefer to view it # this way, 4+ECX bytes past x).