Switch Case Statement Compiler Design
Case Statement
The “case” or “switch” statement is available in various languages. The following is the syntax for the case statement:
switch (E) { case V1: S1 case V2: S2 .... case Vn-1: Sn-1 default: Sn }
Translation of Switch Statement
The translation scheme for the above code is shown below:
Code to evaluate E into T
goto test L1: code for S 1 goto next L2: code for S 2 goto next ..... Ln-1: code for Sn - 1 goto next Ln: code for Sn goto next test: if t = 1 goto L1 if t = 2 goto L2 ..... if t = Vn-1 goto Ln - 1 goto Ln next:
- When we see the switch keyword, two labels test and next and a temporary variable t are generated.
- When we see the case keyword, a new label Li is created and entered into the symbol table. It is used to store the value Vi of the constant Li, or a pointer to the symbol table entry for Li is placed in the queue.