2018-12-22 - In IL: Print the Alphabet (break, continue)
In IL
- Part 1 - Introduction
- Part 2 - Variables and Types
- Part 3 - Variables in Visual Basic .NET
- Part 4 - Instructions and the Stack
- Part 5 - Volume of a Cylinder (Operations)
- Part 6 - Branching Instructions
- Part 7 - Largest of Two Numbers (if-else)
- Part 8 - Largest of Three Numbers (If-ElseIf-Else)
- Part 9 - Switch instruction
- Part 10 - Grade Analyser (switch)
- Part 11 - Prize Calculator (switch-2)
- Part 12 - VB Grade Analyser (Select)
- Part 13 - Loop Instructions
- Part 14 - Print the Alphabet (while)
- Part 15 - Print the Alphabet (do while, for)
- Part 16 - Print the Alphabet (Do Until)
- Part 17 - Print the Alphabet (break, continue)
- Part 18 - Array Instructions
- Part 19 - Summing Arrays
- Part 20 - Other Instructions
- Part 21 - Assemblies
- Part 22 - Class Definitions
- Part 23 - C# Classes and Structs
- Part 24 - VB Classes, Modules and Structures
- Part 25 - Field Definitions
- Part 26 - Field Declarations
One final aspect of looping that we haven't looked at yet are the use of break and continue statements. These statements allow you more control over how loops progress. break statements stop the loop and move to the next statement after the loop while continue statements stop the current loop and moves execution onto the next iteration. We are going to start by looking at the same for loop we had before but with some break and continue statements added.
This loop skips over all "even" letters and stops the loop when we hit the letter k. Now let's look at the compiled code.
This looks very close to our previous for loop but with extra code to check for even letters and the letter k. In the first case we branch to the incrementing part of the loop and continue on from there. In the second case we branch to the first statement after the loop. Now we are going to make those same modifications to the while loop we had before.
Now if we compile this we expect to see the same code as our for loop since the original fore loop and while loop compile to the same code.
Now you might say the compiled code is identical to the compiled code for the for loop and you would almost be right except for one important distinction. The continue part branches to the loop conditional check and not the increment part like the for loop does. This causes the program to go into an infinite loop and never exit.
As I mentioned when we looked at for loops the main difference between for loops and while loops is what is and isn't a part of the loop from the compiler's perspective. In the for loop case the incrementing is part of the loop so the compiler makes sure that's ran even if we use a continue. In the while case we are responsible for the incrementing so the compiler ignored it and goes straight to the conditional check. This is something to keep in mind when you are using break or continue.
Next time we're going to look at some array instructions.
Comments: