Switch and case

From Tux
Revision as of 17:48, 23 January 2018 by Williams (talk | contribs) (Created page with "'''<code>switch</code> and <code>case</code>''' are a pair of commands built into C++ (and many other programming languages) that operate similar to the <code>if</code> statem...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
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)          // if statement version
{
     statement1;
     statement2;
}
else if (x == 2)
{
     statement3;
     statement4;
}
else
{
     statement5;
     statement6;
}

switch (x)
{
     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