Switch & Case unclear to me
#1

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.
Reply
#2

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.
Reply
#3

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
    }
}
Reply
#4

Aaah okay. I pretty much understand it now.
Thanks for the effort put in the mini tuts
Reply
#5

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.
Reply
#6

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)
Reply
#7

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
Reply
#8

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.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)