Difference between revisions of "Switch and case"
(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...") |
|||
Line 10: | Line 10: | ||
cin >> x; | cin >> x; | ||
− | if (x == 1) | + | if (x == 1) |
{ | { | ||
statement1; | statement1; | ||
Line 26: | Line 26: | ||
} | } | ||
− | switch (x) | + | switch (x) // switch version (equivalent to above) |
{ | { | ||
case 1: | case 1: |
Revision as of 17:49, 23 January 2018
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 onecase
, the statements in followingcase
will execute - There is no requirement for a
default
section