Switch and case

From Tux
Jump to: navigation, search

switch and case are a pair of commands built into C++ (and many other programming languages) that operate similar to the if statement. An ideal situation to use them is when there is a sufficiently large number of finite options, for example a text-based menu with valid options of 1, 2, 3, 4, and 5.

switch can only be used with expressions that evaluate to integers, such as a logical comparison (result is 0 or 1), a char, or any non-floating-point expression.

The following code illustrates how switch and case work:

int x;

cin >> x;

if (x == 1)    
{
     statement1;
     statement2;
}
else if (x == 2)
{
     statement3;
     statement4;
}
else
{
     statement5;
     statement6;
}

switch (x)          // switch version (equivalent to above)
{
     case 1: 
             statement1;
             statement2;
             break;
     case 2: 
             statement3;
             statement4;
             break;
     default: 
             statement5;
             statement6;
}


Additional notes:

  • If break is not placed after the statements for one case, the statements in following case will execute
  • There is no requirement for a default section
  • There may be scope issues regarding declaring variables inside a case, in which case the declaration (and associated statements) can be enclosed in { }