CASE STATEMENTS
The “switch” or “case” statement is available in a variety of languages. The switch-statement syntax is as shown below :
Switch-statement syntax s
witch expression
begin
case value : statement
case value : statement
..
case value : statement
default : statement
end
There is a selector expression, which is to be evaluated, followed by n constant values that the expression might take, including a default “value” which always matches the expression if no other value does. The intended translation of a switch is code to:
1. Evaluate the expression.
2. Find which value in the list of cases is the same as the value of the expression.
3. Execute the statement associated with the value found.
Step (2) can be implemented in one of several ways :
By a sequence of conditional goto statements, if the number of cases is small.
Syntax-Directed Translation of Case Statements:
Consider the following switch statement:
switch E
begin
case V1 : S1 case V2 : S2
case Vn-1 : Sn-1
default : Sn
end
This case statement is translated into intermediate code that has the following form : Translation of a case statement
code to evaluate E into t goto test
L1 : code for S1 goto next
L2 : code for S2 goto next
Ln-1 : code for Sn-1 goto next
Ln : code for Sn goto next
test : if t = V1 goto L1 if t = V2 goto L2
if t = Vn-1 goto Ln-1 goto Ln
next :
To translate into above form :
As expression E is parsed, the code to evaluate E into t is generated. After processing E , the jump goto test is generated.
case V1 |
L1 |
|
case V2 |
L2 |
|
case |
Vn-1 Ln-1 |
|
case |
t Ln |
|
label next
where t is the name holding the value of the selector expression E, and Ln is the label for the default statement.
1. What is the purpose of case statements in intermediate code generation? | ![]() |
2. How are case statements represented in intermediate code? | ![]() |
3. Can case statements handle floating-point values in intermediate code generation? | ![]() |
4. How do case statements handle default cases in intermediate code generation? | ![]() |
5. Are case statements limited to a specific number of branches in intermediate code generation? | ![]() |