switch – no break
If in a
switch statement a case
alternative does not end with a
break,
the statements associated with all subsequent cases are executed until a
break is found.
Given an
int variable:
int a;
the
switch statement below checks
a’s value. If it is 3, the statement
associated with it is executed and since there is no
break the statement associated with
case 4 is executed; at which point
a
break is found and the
switch is exited. If
a’s value is 1, the statements
associated with it would be executed and since there are none and there
is no
break the statement associated
with
case 2 is executed; at which
point a
break is found and the
switch is exited. If
a’s value is 2 or 4 or does not match
either 1, 2, 3, or 4, the
switch
reserves no surprises.
switch(a)
{
case 1:
case 2:
cout << "you entered either 1 or 2";
break;
case 3:
cout << "you entered 3\n";
case 4:
cout << "you entered either 4 or 3\n";
break;
default:
cout << "you did not enter either 1, 2, 3 or 4";
}
A working example follows.
Example
#include <iostream>
using namespace std;
int main()
{
cout << "Enter a value, please ";
int a;
cin >> a;
switch(a)
{
case 1:
case 2:
cout << "you entered either 1 or 2";
break;
case 3:
cout << "you entered 3\n";
case 4:
cout << "you entered either 4 or 3\n";
break;
default:
cout << "you did not enter either 1, 2, 3 or 4";
}
}
Output with input equal to 1
Enter a value, please 1
you entered either 1 or 2
Output with input equal to 3
Enter a value, please 3
you entered 3
you entered either 4 or 3