Switch

From Game Editor

Revision as of 18:45, 25 November 2009 by Asmodeus (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. The "wasd" movement example might be written like this with if statements:

if ( keydown == 'w' )
{
  y -= 5;
}
else if ( keydown == 'a' )
{
  x -= 5;
}
else if ( keydown == 's' )
{
  y += 5;
}
else if ( keydown == 'd' )
{
  x += 5;
}
else
{
  PlaySound("annoying-beep.wav", 1, 1);
}

Even though this code is still clear for this simple example, the switch statement is much less to type.