Difference between revisions of "Switch and case"
Line 46: | Line 46: | ||
* If <code>break</code> is not placed after the statements for one <code>case</code>, the statements in following <code>case</code> will execute | * If <code>break</code> is not placed after the statements for one <code>case</code>, the statements in following <code>case</code> will execute | ||
* There is no requirement for a <code>default</code> section | * There is no requirement for a <code>default</code> section | ||
+ | * There may be issues regarding declaring variables inside a <code>case</code>, in which case the declaration (and associated statements) can be enclosed in <code>{ }</code> -- this has to do with scope issues |
Revision as of 17:50, 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 - There may be issues regarding declaring variables inside a
case
, in which case the declaration (and associated statements) can be enclosed in{ }
-- this has to do with scope issues