2016-11-06 - In IL: Switch instruction
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
Along with the branching instructions that we have already seen there's a special multi-branching instruction. It is used in situations where there are multiple possible outcomes based the value of a single input.
switch
Instruction | Binary Format |
---|---|
switch | 0x45 <uint32> <int32> ... <int32> |
The switch instruction is unique because its encoding is variable length. The encoded instruction contains a value, the uint32, that indicates the number of subsequent int32 values. These int32 values are the targets of the instruction and are the same as the int32 values that showed up when we looked at branching instructions. In IL assembly the uint32 would be computed based on the number of arguments, usually labels, to the switch instruction.
The switch instruction works by popping a value off of the stack and then using that value as an index into the instruction's target list. The instruction then jumps to the instruction indicated by the target at that index. If the value is 0 then the instruction jumps to the instruction indicated by the first target. If the value is 1 then the instruction jumps to the instruction indicated by the second target. If the value is greater than the number of targets then the instruction does nothing and execution moves on to the next instruction.
Next time we will look at some uses of the switch instruction.
Comments: