Loops
Files used -> 6-for.c, 6-for.exe, 6-1-for.c, 6-1-for.exe, 6-2-while.c, 6-2-while.exe.
Last updated
Files used -> 6-for.c, 6-for.exe, 6-1-for.c, 6-1-for.exe, 6-2-while.c, 6-2-while.exe.
Last updated
If we think of loop, we can say its something that happens repeatedly forever or until some condition is met.
Here, in this image, We can see a loop (highlighted), which is coming back to where it started from.
In Block 1, we see 0 value assigned to var_4. Then a unconditional jump is taken to block 2, where var_4 is compared with 5. If var_4 is greater than or equal to 5, execution will move to loc_40102F (Block 5).
But the value of var_4 is 0, so it will move to Block 3 where we have some printing going on, and then Block 4 comes into picture, where value of var_4 is incremented by 1. Now the value is 1.
After which it will go to the start, i.e. block 2. Inside which var_4(value of 1) is compared to 5 and same execution path goes on. Then in Block 4 var_4 becomes 2.
This cycle will continue.
Now, after a few iterations when in Block 4 the value of var_4 is incremented and it becomes 5. Now again it goes to Block 2, and var_4 (value 5) is compared with 5. Now our condition (jge, jump if greater or equal to) satisfies and it moves to loc_40102F (Block 5), where we have return value of 0 and epilogue).
So, this loop is starting from 0, printing something and continues till 5 times.
Lets see the source code and check.
6-1-for.exe can be used for practice along with source code 6-1-for.c
Here also, we can see that we have a loop structure, where the execution goes back to initial block.
Starting with Block 1, we see prologue and moving value 0 in var_4. Then moving to block 2, a comparison is done between var_4 and 5. Same comparison again jge, jump if greater or equal to 5.
Initially, var_4 will be lesser than 5 it will move to block 3. Where we have some printing instructions and adding 1 to var_4. And again moving back to block 2.
Lets see the source code →
We can see the difference in disassembly of both. The difference comes in incrementing the counter value. In for loop, the increment is happening in different block whereas in while loop increment is happening in same block where print function is executed.