<< Click to Display Table of Contents >> Navigation: Concordance Programming Fundamentals > Using Conditional Statements and Loops > Switch Statement |
A switch-statement allows you to compare a single value to a series of constants. You can think of a statement as the switch on a railroad. Flip the switch one way and your train goes to the left. Flip the switch the other way and your train goes to the right. Unlike a railroad switch, a switch-statement in programming can have more than two different alternatives.
The following sample describes the structure for a switch-statement:
switch (some value to check) { case value1: doSomething(); break; case value2: doSomethingElse(); break; default: doTheRest(); break; } |
Notice the four keywords here: switch, case, break and default:
•The first line contains the switch statement. This is the value that CPL will use to determine which of the case statements to execute.
•Each case statement contains one possibility for the switch value that you wish to write code about. You can have as many case-statements as you need in order to process each switch value. In the example below, there are 5 different case statements representing the five different vowels.
•The break statement tells CPL to stop processing the case statement and drop out of the switch-statement.
•The default statement is optional. If the value you are checking does not match any of the case statement values, CPL will execute the code referenced by the default-statement.
Note the use of colons (:) after the case-statements and default-statement. These are required.
the following example counts the number of times a vowel appears. You can write the following section of code, using a compound if-statement:
if ((myLetter == 'a') or (myLetter == 'e') or (myLetter == 'i') or (myLetter == 'o') or (myLetter == 'u')) { vowels = vowels + 1; } |
Alternately, you could also write the code using a switch-statement.
switch (myLetter) { case 'a': vowels = vowels + 1; break; case 'e': vowels = vowels + 1; break; case 'i': vowels = vowels + 1; break; case 'o': vowels = vowels + 1; break; case 'u': vowels = vowels + 1; break; } |