Computer Science 301 - 2001


Tutorial for week 21 - Code generation for a CASE statement

In earlier discussions we have suggested adding a case/switch statement to the CS301 language, with syntax modelled on that found in Modula-2:

  CaseStatement = "CASE" Expression "OF"
                    OneCase { "|" OneCase }
                    "DEFAULT" ":" StatementSequence
                  "END" .

  OneCase = [ Range { "," Range } ":" StatementSequence ] .

  Range = IntConst [ ".." IntConst ] .

  IntConst = [ "+" | "-" ] number .

Here is a simple example of such a statement:

    CASE x + y OF
        1 :      Write('One')
      | 4 :      Write('Four');
      | 5 .. 8 : Write('Five to eight')
      DEFAULT :  Write('Not 1, 4, 5, 6, 7, 8')
    END

and here is a rather more bizarre one:

    CASE x OF
      |  { empty }
      |  { empty }
      |  1 : Write('One')
      |  2 .. 12345 : { empty }
      DEFAULT : Write('Not in range 1 - 12345')
    END;

or. if you like that sort of nonsense

    CASE x of
      DEFAULT :
    END;

The motivation for requiring the DEFAULT option is, of course, safety - if a user really wants to "do nothing" when the expression matches none of the (usually small) set of particular labels, then this must be explicitly coded with a DEFAULT option. This prevents errors from overlooking conditionss that "should never arise" but sometimes do, as would happen with CASE statements of the form

     CASE yearOfStudy OF
         1 : Write('First year student')
       | 2 : Write('Second year student')
       | 3 : Write('Third year student')
     END

and forgetting that some students are enrolled for four-year degrees.

Discuss how one would perform semantic checking and generate code for such statements for our stack machine. Feel free to extend the machine's set of op-codes if necessary - that is in the spirit of using an interpretive approach! Furthermore, is there any need to restrict the labels to the form suggested above. Why not allow statements like these?

     CASE  X > Y OF
       TRUE : Write('X>Y')
       FALSE : Write('X<=Y')
       DEFAULT : { empty for obvious reasons }
     END

     CASE X OF
       Max - 10 .. Max + 10 : Write('In range max-10 .. max + 10')
       2 * Max : Write('twice Max')
       DEFAULT :
     END


Home  © P.D. Terry