Switch & Case unclear to me -
arjanforgames - 08.08.2013
I don't really understand where a switch and case are used for.
Is there a good purpose or is it used to shorten things? I've searched but couldn't find a clear explanation.
Hopefully you can give me a clear explanation and maybe an example.
Re: Switch & Case unclear to me -
[XST]O_x - 08.08.2013
pawn Код:
if(a == 7 || a == 8)
//equals to:
switch (a)
{
case 7, 8: {
///Something
}
}
It can shorten at some cases. For example, if you want only specific numbers.
pawn Код:
if(a == 7 || a == 31 || a == 98 || a == 104 || a == 1009)
{
//stuff
}
//Equals to
switch(a) {
case 7, 31, 98, 104, 1009: {
//Stuff
}
}
Or just for a range of values... Lets say... 1 to 99:
pawn Код:
if(a >= 1 && a <= 99)
{
//Something
}
else if(a >= 100 && a <= 199)
{
//Something
}
else if(a >= 200 && a <= 299)
{
//Something
}
else
{
//Something
}
Just like doing:
pawn Код:
switch (a)
{
case 1...99:
{
}
case 100...199:
{
}
case 200...299:
{
}
default: //Default equals to 'else' - when no other option is available, default is called.
{
}
}
So yeah, if you know
when to use it, it can save tons of space.
Re: Switch & Case unclear to me -
Konstantinos - 08.08.2013
What would you prefer?
pawn Код:
if( vehicleid == 0 || vehicleid == 2 || vehicleid == 4 || vehicleid == 6 || vehicleid == 8 || vehicleid == 10 || vehicleid == 12 || vehicleid == 14 || vehicleid == 16 || vehicleid == 18 || vehicleid == 20 )
{
// Do something
}
// OR
switch( vehicleid )
{
case 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20:
{
// Do something
}
}
Re: Switch & Case unclear to me -
arjanforgames - 09.08.2013
Aaah okay. I pretty much understand it now.
Thanks for the effort put in the mini tuts
Re: Switch & Case unclear to me -
Scenario - 09.08.2013
Oh and a switch statement is generally quicker than an if-else structure. Not majorly, but I'm sure if you got down to the nitty gritty, you would be surprised.
Re: Switch & Case unclear to me -
Vince - 09.08.2013
The main difference is that a switch evaluates the expression only once, whereas an if-else structure re-evaluates the expression every time. This is even more cumbersome if you don't assign the return value of a function to a variable. Something like this, however very bad it is, seems very common:
pawn Код:
if(GetVehicleModel(vehicleid) == 411 || GetVehicleModel(vehicleid) == 520 || GetVehicleModel(vehicleid) == 600)
Re: Switch & Case unclear to me -
Misiur - 09.08.2013
Quote:
Originally Posted by [XST]O_x
pawn Код:
switch (a) { case 1...99: { } case 100...199: { } case 200...299: { } default: //Default equals to 'else' - when no other option is available, default is called. { } }
|
Just in case - there are two dots, not three
Re: Switch & Case unclear to me -
Scenario - 09.08.2013
Vince, I cringe when I see that in people's code. God that was an awful think for people to do; I'm glad I hardly see it nowadays.