Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

1. ## switch statement help please

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

• 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.
Code:
if(result==0)
{
home won
}
else
{
if(result==1)
{
draw won
}
else
{
guests won
}
}
now with switch that could look like this
Code:
switch(result)
{
case 0:home won;break;
case 1:draw won;break;
case 2:guests won;break;
}

• Well. here it goes:
Code:
if(a==b){
/* do something */
}else if(a==c){
/* do something */
}else{
/* do something */
}
can be written as
Code:
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:
Code:
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:
Code:
switch(true){
case (a>b):
/* do something */
break;
case (a<b):
/* do something */
break;
case (a==b):
/* do something */
break;
}

• I'd just like to say a big thank you to you all for your invaluable help.

Cheers!

•

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•