...

View Full Version : switch statement help please



charter
03-15-2004, 09:26 PM
I have heard something about theswitch statement being used instead of if/else statements.

I have looked through a few tutorials on the difference and use of the switch statement without success.

Can anyone please point me in the right direction of a tutorial on the statement or if possible let me have an example of the difference between the switch and if/else statements.

All help much appreciated

A1ien51
03-15-2004, 09:44 PM
You look at the page on JavaScriptKit?
http://www.javascriptkit.com/javatutors/switch.shtml

or on w3schools
http://www.w3schools.com/js/js_conditionals.asp

Eric

Garadon
03-15-2004, 09:47 PM
The switch is not used to replace simple if elses but rather used where
different values of a variable migth give diferent result. for eksample if you took any sports match it has 3 posible out comes:
home won=0
draw=1
guests won=2

now with is that would look like this.


if(result==0)
{
home won
}
else
{
if(result==1)
{
draw won
}
else
{
guests won
}
}


now with switch that could look like this


switch(result)
{
case 0:home won;break;
case 1:draw won;break;
case 2:guests won;break;
}

liorean
03-15-2004, 09:48 PM
Well. here it goes:

if(a==b){
/* do something */
}else if(a==c){
/* do something */
}else{
/* do something */
}can be written as
switch(a){
case b:
/* do something */
break;
case c:
/* do something */
break;
default:
/* do something */
}
This makes it easy to compare a single variable to multiple values. However, there are some special properties of the switch statement, such as fall through, which means that if you leave out the break statement the next case will also be executed:
var
b=1;
switch(a){
case 9:
b*=9;
case 8:
b*=8;
case 7:
b*=7;
case 6:
b*=6;
case 5:
b*=5;
case 4:
b*=4;
case 3:
b*=3;
case 2:
b*=2;
default:
}
This means that if a is, say, 5, b will be 5*4*3*2*1=120, since it falls through. Note that you can break it at any point.

Also, another thing you can use the switch statement for is to do multiple entirely different comparisons in the following manner:
switch(true){
case (a>b):
/* do something */
break;
case (a<b):
/* do something */
break;
case (a==b):
/* do something */
break;
}

charter
03-16-2004, 09:39 AM
I'd just like to say a big thank you to you all for your invaluable help.

Cheers!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum