I have previously talked about whether the switch statement should exist in languages (Should the switch statement exist?). The switch statement is a means of creating a multi-way if statement, but it has always been somewhat maligned. Why? I would imagine largely because of C. But how did it get to where it is today?
Fortran had no concept of a switch statement, but then this is not surprising considering its unstructured nature in its early years (i.e. build your own using GOTO). Algol 60 had the concept of a switch, but it was more in the way of an identifier which represents a switch.It looked like this:
switch I := L1, L2, L3,...., Lp
Where Lx is a label. How did this work? Well, consider the following piece of code (from Description of Algol 60):
switch wernik := arica, acryl, m17, larix
The switch wernik allows one of the four labels listed. So wernik selects the label acryl. This could then be used to construct a multi-way control structure:
begin switch wernik := arica, acryl, m17, larix; goto wernik[k]; arica : ; ... goto common; acryl : ; ... goto common; m17 : ; ... goto common; larix : ; ... common: end
Pleasant? I think not. But the concept is there – the programs logic follows one of four possible branches, depending on the value of k. This was essentially a somewhat nicer version of Fortrans computed GOTO statement, although it wasn’t a control structure per se, more of a set really. PL/I (1964) invoked the multi-way by means of a select structure:
select; when (C1) S1; when (C2) S2; when (C3) S3; otherwise S4; end;
Interestingly it was one of the few to use the when–otherwise combination. The modern structure of the case statement was originally proposed by Hoare and included by Hoarre and Wirth in Algol-W. This statement had the form:
case C of begin S1; S2; ... ; Sn end
The integer expression (C) is evaluated within the range 1 to n. It basically evaluates the statement (Sx) whose ordinal value is the same as C. An example of a piece of code using this might be:
case K of begin H(I) := -H(I); begin H(I+1) := H(I+1) + H(I); I := I + 1 end; begin H(I+1) := H(I+1) * H(I); I := I + 1 end; begin H(I) := H(I+1) + H(I); I := I + 2 end end
The concept was not bad, but relied on the value of K being 1 to 4. What if its value was 5? There was no alternative, so one assumes the actions in the case would be skipped. How to fix this? That was to be up to Algol 68.