PDA

View Full Version : Switch & Case unclear to me


arjanforgames
08/08/2013, 09:30 PM
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.

[XST]O_x
08/08/2013, 09:40 PM
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.

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:

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:

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.

Konstantinos
08/08/2013, 09:43 PM
What would you prefer?

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
}
}

arjanforgames
09/08/2013, 07:03 AM
Aaah okay. I pretty much understand it now.
Thanks for the effort put in the mini tuts :)

Scenario
09/08/2013, 07:11 AM
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.

Vince
09/08/2013, 07:18 AM
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:

if(GetVehicleModel(vehicleid) == 411 || GetVehicleModel(vehicleid) == 520 || GetVehicleModel(vehicleid) == 600)

Misiur
09/08/2013, 07:20 AM
O_x;2652579']
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

Scenario
09/08/2013, 07:46 AM
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.