Pergunta

The question in the book shows the following loop:

    mov ecx, -1
forD: .
      .                ; loop body
      .
      loop forD

The question asks "how many times is each loop body executed?"

The answer in the back of the book says 4,294,967,295, but why? What's the significance of this number? Is this supposed to be a never-ending-loop?

Foi útil?

Solução 2

-1 is 0xFFFFFFFF in 32-bit 2's complement, which is 4294967295 (232 - 1) in unsigned decimal

The loop time depends on the loop body. But in current CPUs you can run a short loop several billion times within a few seconds or less

Outras dicas

loop works as follows:

  1. decrement (e)cx by 1
  2. check if it is 0
  3. if not, jump to the specified offset/label
  4. if 0, continue with the next instruction

-1 equals to 4294967295 unsigned, which in turn results in that number of loop iterations.

There are some catches using loop:

  • Loop first decreases the counter register.Putting there 0 will not result in zero repetitions but in 4294967296, because the first decreasing will result in -1 in (e)cx. Accordingly, putting 1 there will result in zero repetitions. Please note that this still executes the looped instructions once - if the loop destination is before the loop instruction.

  • Loop is a 2byte opcode. First byte is E2 for the instruction itself, so there is only one byte left for jump destination offset. That offset is signed, so you can only loop within -128..127 bytes distance.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top