Switch Statements
switch (controlling expression){
case matched
value1:
stmta;
stmtb;
break;
case matched
value2:
stmta;
stmtb;
break
default: stmts;
}
The
controlling expression has to be an ordinal data type (integer or
character). You can’t have a double or a
float.
Used
when selection is based on the alue of a single
variable or a simple epression.
In
a switch statement, execution starts at the first matched value, and continues
until the ending curly bracket or a break statement, whichever comes
first.
Break
statements will “break” you out of the current level of nesting; it will bring
you to the statement following the nearest end curly bracket.
#include
<iostream>
using
namespace std;
int
main()
{
int
grade;
char gradebookentry;
cout
<< "What was your grade on the latest exam? " ;
cin
>> grade;
switch (grade) {
case 99: cout << "One more point" << endl;
gradebookentry = 'A';
break;
case 98: cout << "FANTASTIC!" << endl;
gradebookentry = 'A';
break;
case 97: cout << "Great job!" << endl;
gradebookentry = 'A';
break;
default: cout << "Please apply more effort!" << endl;
gradebookentry = 'E';
}
cout
<< "Your grade so far is:
" << gradebookentry << endl;
return 0;
}
What was
your grade on the latest exam? 98
FANTASTIC!
Your
grade so far is: A
Press any
key to continue
What was
your grade on the latest exam? 77
Please
apply more effort!
Your
grade so far is: E
Press any
key to continue
What
happens when a break statement is missing?
switch (grade) {
case 99: cout <<
"One more point" << endl;
gradebookentry
= 'A';
break;
case 98: cout <<
"FANTASTIC!" << endl;
gradebookentry
= 'A';
case 97: cout <<
"Great job!" << endl;
gradebookentry
= 'A';
break;
default: cout <<
"Please apply more effort!"
<< endl;
gradebookentry
= 'E';
}
cout << "Your
grade so far is: " << gradebookentry << endl;
What
was your grade on the latest exam? 99
One
more point
Your
grade so far is: A
Press
any key to continue
What
was your grade on the latest exam? 98
FANTASTIC!
Great
job!
Your
grade so far is: A
Press
any key to continue
If
there are no break statements execution “falls” through to the next alternative
and everything else afterwards is executed.
switch (grade) {
case 99:
case 98:
case 97: cout << "Great
job!" << endl;
gradebookentry
= 'A';
break;
default: cout <<
"Please apply more effort!"
<< endl;
gradebookentry
= 'E';
}
cout << "Your
grade so far is: " << gradebookentry << endl;
What
was your grade on the latest exam? 99
Great
job!
Your
grade so far is: A
Press
any key to continue
What
was your grade on the latest exam? 98
Great
job!
Your
grade so far is: A
Press
any key to continue
What
was your grade on the latest exam? 97
Great
job!
Your
grade so far is: A
Press
any key to continue
What
was your grade on the latest exam? 77
Please
apply more effort!
Your
grade so far is: E
Press
any key to continue