Switch

From Game Editor

Revision as of 08:42, 31 August 2008 by Edh (Talk | contribs)
(diff) ← Older revision | Current revision (diff) | Newer revision → (diff)
Jump to: navigation, search

A switch statement is a special instance of an if else if else ... statement.

A switch statement takes the following form:

switch ( expression ) {
  case constant_1 : 
    statements;
  case constant_2 : 
    statements;
  ...
  default : 
    statements;
}

Example:

 char keydown = getKey();
 switch ( keydown ) {
   case 'w':
     y -= 5;
     break;
   case 'a':
     x -= 5;
     break;
   case 's':
     y += 5;
     break;
   case 'd':
     x += 5;
     break;
   default:
     PlaySound("annoying-beep.wav", 1, 1);
 }

The default condition is optional.

The break statement in each case condition is optional, but recommended. If you do not include a break for each case, each subsequent case would also be executed.

Bad example:

 char keydown = getKey();
 switch ( keydown ) {
   case 'w':
     y -= 5;
   case 'a':
     x -= 5;
   case 's':
     y += 5;
   case 'd':
     x += 5;
   default:
     PlaySound("annoying-beep.wav", 1, 1);
 }

In the bad example, if keydown has the value 'w', then y will decremented by 5, x will be decremented by 5, y will incremented by 5, x will be incremented by 5 and the annoying sound will be played.

A switch statement may be easier to read than nested if statements.