In: Computer Science
A Switch/case statement allows multiway branching based on the value of an integer variable. In the following example, the switch variable s is specified to be assumed to be one of three values of [0, 2], and a different action for each case becomes:
case 0: a = a - 1; break;
case 1: a = a + 2; break;
case 2: b = 3 * b; break;
Shows how such statements can be compiled into MiniMIPS assembly instructions.
Switch statement
The switch statement is one of the statements we had in computer programming. It is a multiway branch statement. Using the switch statement we can choose one of the code blocks to be executed. As in, using a variable, we test the value of the variable, against list of values. Each value of the variable is called a case.
Given
problem:
We have a variable ‘s’ with the possible values from the set
[0,2]
We also have cases given:
1. case 0: a=a-1;
break;
2. case 1: a=a+2;
break;
3. case 2: b=3*b;
break;
The computer programming
code/pseudocode can be as follows:
switch (s)
{
case 0: a=a-1;
break;
case 1: a=a+2;
break;
case 2: b=3*b;
break;
default: a = 0; //assume for example
break; //suppose
}
Coming to the
MINIMIPS assembly instructions:
Using the mapping as
follows:
a: s0, b: s1, s: s2
Code in MIPS
lw $s0,a # load a from memory--assume
lw $s1,b # load b from memory--assume
bne s2, 0, L1 # case s!=0
sub s0, s0, 1 # case s=0 so a=a-1
b Exit # end of case so Exit
L1:
bne s2, 0, L2 # case s != 1
addi s0, s0, 2 # case s=1 so a=a+2
b Exit # end of case so Exit
L2:
bne s2, 0, Exit # case s != 2
muli s1, s1, 3 # case s=2 so b=b*3
Exit: