teach-ict.com logo

THE education site for computer science and ICT

5. SWITCH / CASE statement

You have seen how the IF statement allows you to test whether an instruction should run. It is a very common requirement that you want to test for a set of values rather than just a single one.

The long way of doing this is to write

if (x = 'Monday') then ....

if (x = 'Tuesday)' then ....

if (x = 'Wednesday') then ...

and so on. This works but it seems to take an awful lot of source code.

What you need is a SWITCH construct. The purpose of a switch statement is to test the condition only once then branch to one of a set of choices.

Unfortunately every language seems to have a very different way of laying out a switch statement but the pseudo-code for the general idea is shown below

  SWITCH x
  	
     CASE 'Monday': Print ()
     CASE 'Tuesday': Work_salary()
     default: Store()
  END    
  

It begins with a test for the condition of x, which is the SWITCH part. Then the appropriate CASE is run depending on the value of x. In this case it will handle x being Monday or Tuesday. Should x be neither of those values then the DEFAULT statement is run. You can of course have more than two cases and you can have many statements within each case block.

As I say, every language seems to implement this in a different way. For instance

'C' language

  switch (x){
    case 'monday':
    	Print ();
        break;
    case 'tuesday':
    	Work_salary()
        break;
    default:
       Store();
    	break;		        
  }
  

C insists on having a 'break' statement to stop the next case also being run.

Perl language

(another popular web server language) it looks like

  use feature 'switch'
    given (x) {
  	when ("monday") {
    	Print ();
    }
  	when ("tuesday") {
    	Work_salary()
    }
    default:
       Store();
  }		        
  

In this language the CASE statement become 'when'.

But the essential element is that there is a method to test the state of a variable then jumping to one of a set of statement blocks. You can write an algorithm in pseudo-code which may then be coded in any number of different languages.

 

Challenge see if you can find out one extra fact on this topic that we haven't already told you

Click on this link: Using SWITCH and CASE