switch/case Statement

The switch statement operates like a series of if statements on the same condition. It makes the code clearer and easier to maintain in one value is being tested multiple times. However, only integers can be used as the comparison in a case statement (true integer constants can be used, as long as they are properly defined).


The following examples have the same effect:

int x = 0;
// if block - silly!
if (x == 0)
{
     // statements ...
}
else if (x == 1)
{
     // statements ...
}
else if (x == 2)
{
     // statements ...
}
else
{
     // statements ...
}

// switch block
// the above if/else block is functionally equivalent to the below
// switch statement
switch (x) 
{
case 0:
     // statements ...
     // without a break testing would continue
     // in this example if we didn't use a break, the default
     // condition would also evaluate as true if x == 0
     break;  
case 1:
     // statements ...
     break;
case 2:
     // statements ...
     break;
default:
     // statements ...
     break;
}

The variable x is passed into the switch statement and compared to the value after the case statement. If none of the case statements equal x then the optional default code block is executed.


It is important to include the break statement at the end of each case code block to escape from of the switch statement, or the proceeding cases will execute also (however, sometimes this is a desired effect).

It should also be noted that you cannot initialize or declare a variable within a case statement.




 author: Ryan Hunt, editor: Grimlar, additional contributor(s): Rich Dersheimer, Simon Hassall, Seth Ellsworth