PocketC Language (v3): switch statement

Postby cao on Sat Mar 24, 2001 12:31 am

The switch statement is basically an enhanced version of the "if-else" statement that is more convenient to use when you have code that needs to choose a path from many to follow. Let's have a look at this statement's general syntax:

<pre id=code><font face=courier size=2 id=code>
switch (expression){
case value1:
case value2:
default : statement;
</font id=code></pre id=code>
<pre id=code><font face=courier size=2 id=code>
string favoritemovie;
favoritemovie = "Titanic";
switch (favoritemovie)
case "Titanic": alert("Not a bad choice!")break;
case "Water World": alert("No comment")break;
case "Scream 2": alert("It has it\'s moments")break;
default : alert("I\'m sure it was great"); break;
</font id=code></pre id=code>

The switch statement always begin with the keyword "switch", plus a required parameter that contains the expression (or variable) you wish to evaluate. This expression is then matched against the value following each "case", and if there is a match, it executes the code contained inside that case. If no match is found, it executes the default statement at the end of the switch statement. In the example code on the right, variable "favoritemovie" contains the name of a person's favorite movie. If his/her selection happens to be either "Titanic", "Waterworld", or "Scream 2", a customized message is alerted. All other selections will simply result in a generic, "I'm sure it was great" message.

A switch statement is essentially the same as a series of "if" and "else-if" statements. "So, what's the point of even having a switch statement", you may ask. Well, it's simple to use, logical in syntax, and most importantly, many programmers swear by it. You don't have to adopt it when writing conditional statements; in fact, you won't even notice a difference.

Another example:
<pre id=code><font face=courier size=2 id=code>
int number;
number = 3;
/* Estimate a number as none, one, two, several, many */
switch(number) {
case 0 : puts("None\n"); break;
case 1 : puts("One\n"); break;
case 2 : puts("Two\n"); break;
case 3 :
case 4 :
case 5 : puts("Several\n"); break;
default : puts("Many\n"); break;
</font id=code></pre id=code>

Edited by - cao on 03/23/2001 18:40:39
Posts: 60
Joined: Tue Dec 05, 2000 4:11 am
Location: USA

Return to PocketC for CE KB

Who is online

Users browsing this forum: No registered users and 1 guest