Why are loops executed one more time than the loop body?

会有一股神秘感。 提交于 2019-12-06 02:15:55
bnm

I think you are confused about what the statement in the book states

When a for or while loop exits in the usual way (i.e., due to the test in the loop header), the test is executed one time more than the loop body.

This means that the loop condition will be tested one more time than the loop body therefore by your example:

for j = 1:3
        j = 1, pass and looped
        j = 2, pass and looped
        j = 3, pass and looped
        j = 4, failed and code executes as written

Here's the pseudo machine code for a for...loop

// int result = 0;
// for(int x = 0; x < 10; x++) {
//   result += x;
// }
MOV edx, 0 // result = 0
MOV eax, 0 // x = 0
.ForLoopLabel:
CMP eax, 10 // FillFlags(x - 10)
JGE .ForLoopFinishedLabel // IF x >= 10 THEN GoTo ForLoopFinishedLabel
// for loop's body
ADD edx, eax // result += x
// end of body
ADD eax, 1 // x++
JMP .ForLoopLabel // GoTo ForLoopLabel
.ForLoopFinishedLabel:
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!