Please explain a switch statement?
Alright so I get it's like a big "if, else" statement, and I know the structure of it, but I'm a little confused with the "case", is the case the current value of the variable? And how do you write a case? Is it: case "value of variable":, or are there no "". Also how do you close it, do you just end it with a }? Thanks!
Answer by DaveA · Feb 13, 2012 at 11:38 PM
var a;
a = something;
switch (a)
{
case 1: // if a is an integer
Debug.Log("a is an integer");
break;
case "1": // if a is a string
Debug.Log("a is a string");
break;
case default:
Debug.Log ("none of the above");
break;
}
The variable named in the 'switch' line is the current value of the variable, of course. Those listed in each 'case' are what to match with. Use the default if you need a catch-all.
Two notes:
1- The break statement ends each case; if missing, the execution continues in the following case code (it's an intended feature)
2- @DaveA, it's only default:, not case default: (at least in UnityScript)
@aldonaletto C# is also just default:
As a side note, in C# if you have any instructions in a case, you must use a break; you can only fall through to the following case if there is no code per case. ie:
string WhatAmI(int i) {
switch(i) {
case 0: // this is ok
case 1:
return "insignificant";
break;
case 2:
Debug.Log("Two!"); // this is not ok
case 4:
return "even";
break;
default:
return "something else";
break;
}
@Datael: actually that's only true for C#; every other language including Unityscript allows fall-through:
var a = 2;
switch (a) {
case 1:
Debug.Log ("1");
break;
case 2:
Debug.Log ("2");
case 3:
Debug.Log ("3");
break;
}
I was intending to only be talking about C# but I guess I didn't make that clear at all did I :)
Edited my comment to make that more clear
Answer by Max_Bol · Aug 28, 2020 at 05:36 PM
While this is an old Question, as there are no accepted answer and the link come up really high on Google, I'll put my 2 cents in and explain the switch statement in a way that almost anybody can understand.
First, as stated by the question, the Switch is a conditional statement or, in simple terms, a "what if" kind of condition. Its use is similar to that of the "if/else" conditional statement, but depending on the port (target device), its internal use is quite different, hence why some loath its use (a.k.a. deeply hate) because it's quite easy to fall into a rabbit hole while using it. (A rabbit hole is a way of saying that you work in circle while never finding a way out of a problem. It's based on Alice in the Wonderland.)
The switch's structure is like this :
switch (condition)
{
case ConditionA:
// Do something.
break;
case ConditionB:
// Do Something Else
break;
case ConditionC:
// Do something else else. ;)
break;
}
Within the parentheses (*) after switch, it requires the source of the condition. It can be any kind of parameters that are set like an integer internally. This is what, for some, makes it different than an "if" statement. What this means is that it can be an integer, a boolean, an Enum, a state, etc. One thing that is important to remember is that it has some limitation as to how deep it can get its value. this means that it might be required to cache the conditional parameter before using it in a Switch statement. This is one of the main difference with an "if" statement as the Switch doesn't complete deep interpretation. While C-Sharp in Unity might allow some leeway around those limitation, this is actually because of how it manage the switch statement internally and this might result in minor performance drop in the long run.
For example, you should not use .count or .length or any kind of "deep" getters directly in the switch, but instead get the getters' value in a pre-made parameter (cached) such as an integer value or whatever. Switch statement takes only pre-cached value.
Something like this:
int Data_Length = 0;
Data_Length = WhateverArray.Length();
switch (Data_Length)
{
default:
// Do something if anything else.
break;
case 2:
// Do Something
break;
case 3:
// Do something else
break;
}
That example isn't the best, but it does give you one thing that switch statement can't do. You can't give imprecise data to a switch() statement like you can in an if() statement.
//This can't be done properly with a switch()
if( Data_Length >= 5){
// Do something
}
else{
// Do something else
}
//To do something like this with a switch, it would have to be like this:
switch (Data_Length){
default :
//Do something else
break;
case 0:
//Do something
break;
case 1:
//Do something
break;
case 2:
//Do something
break;
case 3:
//Do something
break;
case 4:
//Do something
break;
case 5:
//Do something
break;
}
As such, you can't use conditional statement (>=, and <) as cases nor uncached values (like case a + b: wouldn't work)
Another limitation of the switch statement depends on the targeted device. Depending on the target device, Unity might convert the switch to a different statement internally and, in some case, not take the whole switch statement condition which will end up breaking your project. As another example, building a project for Android might break the switch statement as the build will automatically convert the switch to a series of If() statement internally. I made a project to test it out and I created a single function that took an integer in which a single switch statement ran and this managed the whole main menu's buttons effects of a project of mine. A total of 86 conditions (cases) set in the switch statement. Building the Android APK made the cases after 42 to simply not work at all. The exact same project was working 100% on a build for PC and even with a direct conversion to WebGL.
Still, with all those things about the switch statement, what use can this have?
The switch() is lighter, internally, than if() as while the block (cached data) is of similar size, it's actually cut down to only the active case(s) in the CPU (if the switch was not converted during the built). To put it in simple terms, both take around the same amount of memory in the RAM, but while the if() will load its whole conditions (even those that are not active) through the CPU thread, the switch() will only run the case that is active. If you got multiple if() and else() statements in row, like 5, the CPU will have to read all 5 if() and else() statement even if only 1 return true. If you got a switch with 5 cases (including 1 default), the CPU will have to only reach the 1 case that returns true. This makes the switch statement a prime tool with things that have complex ranges of impact on CPU-related performances.
To conclude, switch() statement is the best when you know what you're dealing with and have full control of it. As soon as you enter the realm of "possibilities" or "chances" or "multi-conditional", switch loose all its good side. I also suggest to use a single switch per function. Having multiple switch() within switch() in a single function will be one of the biggest readability-related pain you'll ever face when dealing with codes. Having a switch() that call functions with other switch() allows you to focus one each layer of condition more easily. As I previously stated, the CPU-related performances can be quite efficient with a switch statement. For example, if you use a single scene for multiple game modes, you could use a switch in the Update() function with a single integer to determines which mode is active and controls what is sent to the CPU in real-time.
This essay has gone highly unappreciated. Thanks man!
Answer by Owen-Reynolds · Feb 14, 2012 at 02:47 AM
IMHO, don't waste your time learning switch statements. Learning arrays, functions, classes ... will solve so many programming problems for you. Switches are just bad ifs -- they're one of many failed features, like repeat-until loops. "Bunch of switch statements" is programmer slang for bug-ridden program.
I sympathize with switch-users. I learned and used them -- the old case 'a', 'A':
trick (`toLower` is easier and faster,) leaving off the break
to make lines serve double-purpose ... . But, kill your darlings.
I wouldn't agree that there's no use for switch statements; it's far easier to read switch statements sometimes than long lists of if/else if instructions. They're also helpful for unrolling loops in certain situations, too... But like you say they shouldn't be top priority
Sorry, but no. Switch statements have their place. Yes, they can be abused, like just about every feature there is, but that's not a reason to never use them. (Also, I've used a do/while loop exactly once in recent memory, but it was precisely what I needed in that case.)
Plus this doesn't answer the question. If you want to argue about stuff, that's what the forums are for.
Want to avoid meta-discussion, but RE: Forums vs. Answers:
$$anonymous$$any Q's here are of the form "How do I solve X, using Y." The comments often drift into what they are really trying to accomplish. Sometimes the poster just wanted an excuse to learn Y. But, more often, the answer they accept is about an easier way to solve it.
Say someone hears that switches can be used to swap colors and does some research here. A useful piece of info would be that ifs, which they probably know a lot better, have as much color-swapping power as switches.
The main reason to use switches is for two reasons. to improve readability of a long chain of if else. and for performance. Switches are actually faster than multiple if's or if else's when there are more than 4 or 5 conditions.
Answer by Dik · Feb 14, 2012 at 01:10 AM
Yes is a switch statement the case is the current value of the variable you are checking against. You are correct in that a switch statement work in a very similar way to a bunch of if statements or even if else statements. The upside is that a switch statement is much more efficient because you are only checking the variable once and not checking each "if". The syntax depends on the language you are coding in. If you are using C# you end a case by setting a "break" see syntax below: I have defined "state" as the current "MenuState" and use this switch statement to change what I am drawing. Hope this helps. For further information you can also look at this link: http://msdn.microsoft.com/en-us/library/06tc147t(v=vs.71).aspx
switch (state)
{
case MenuState.DoNothing:
// Do nothing
break;
case MenuState.RenderSelf:
GUI.Window (InGameWindowID, MenuRect(menuSize), doInGameOptionsMenu, "");
break;
case MenuState.RenderSubMenu:
//handle sub-menu rendering here
break;
}
Your answer
Follow this Question
Related Questions
how to make a script that goes to the next scene if you click a gameobject in unity 5 2 Answers
How add(create) a new gameobject on scene on mouse button click. 2 Answers
Missing Reference. 0 Answers
how to make a level block/unblock 1 Answer
Need a Script for Changing Scenes after pressing E to open locked door once a key has been found. 0 Answers