The C++Course provides a general introduction to programming in C++. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details. |
![]() |
Home ![]() ![]() |
||
See also: Chained Conditionals | ||
![]() ![]() ![]() ![]() ![]() ![]() |
||
Switch Statement
It's hard to mention enumerated types without mentioning switch statements, because they often go hand in hand. A switch statement is an alternative to a chained conditional that is syntactically prettier and often more efficient. It looks like this: switch (symbol) {case '+': perform_addition (); break; case '*': perform_multiplication (); break; default: cout << "I only know how to perform addition and multiplication" << endl; break; } This switch statement is equivalent to the following chained conditional: if (symbol == '+') {perform_addition (); } else if (symbol == '*') { perform_multiplication (); } else { cout << "I only know how to perform addition and multiplication" << endl; }
switch statements work with integers, characters, and enumerated \mbox{types}. For example, to convert a Suit to the corresponding string, we could use something like: switch (suit) {case CLUBS: return "Clubs"; case DIAMONDS: return "Diamonds"; case HEARTS: return "Hearts"; case SPADES: return "Spades"; default: return "Not a valid suit"; } In this case we don't need break statements because the return statements cause the flow of execution to return to the caller instead of falling through to the next case. In general it is good style to include a default case in every switch statement, to handle errors or unexpected values.
|
||
Home ![]() ![]() |