- Home /
Switch statement error
Hey guys,
I just "discovered" the switch statement today, and have been trying to figure it out. For some reason, the example I made is not working, and I would like to know why. If anyone can see what's wrong, please post an answer! The code, as well as the error, are bellow.
error CS0152: The label `case -2:' already occurs in this switch statement
switch(DateTime.Today.Month)
{
case 1:
Debug.Log ("case 1");
season = 3;
world.renderer.material = winterGround;
break;
case 2 - 4:
Debug.Log ("case 2 - 4");
season = 0;
world.renderer.material = springGround;
break;
case 5 - 7:
Debug.Log ("case 5 - 7");
season = 1;
world.renderer.material = summerGround;
break;
case 8 - 10:
Debug.Log ("case 8 - 10");
season = 2;
world.renderer.material = autumnGround;
break;
case 11 - 12:
Debug.Log ("case 11 - 12");
season = 3;
world.renderer.material = winterGround;
break;
default:
Debug.Log ("There is an error!");
break;
}
Thanks for your help!
-Gibson
Answer by Hagbard · Apr 08, 2012 at 12:18 AM
"case 2 - 4:" is read as "case 2 minus 4", which translates to -2. same for 5 - 7, etc. A case can only contain one value. But you can do the following:
switch(DateTime.Today.Month)
{
case 1:
Debug.Log ("case 1");
season = 3;
world.renderer.material = winterGround;
break;
case 2:
case 3:
case 4:
Debug.Log ("case 2 - 4");
season = 0;
world.renderer.material = springGround;
break;
case 5:
case 6:
case 7:
...
break;
...
}
If you then call case 2 it will go through all the code until the next break statement. So case 2, case 3, and case 4 will all execute the same code.
Answer by rutter · Apr 08, 2012 at 12:20 AM
Switches are very handy, but I think you might be misunderstanding one crucial detail: switches will only check for equality against individual constant values, not ranges or variables.
You set a number of cases using literal expressions:
case 2 - 4:
case 5 - 7:
case 8 - 10:
I've never seen that done, before, but I believe the compiler is simplifying all of those expressions. And what do they have in common? All of the expressions I quoted will evaluate to the same number:
case -2:
case -2:
case -2:
case -2:
Recognize that number from your error message?
Within a switch, each case value must be unique.
You may have an easier time with other control structures (array indexing, binary searching, a simple series of if-else blocks, or so on), but that seems to be beyond the scope of your original question.
Hagbard's solution might also work, if you're not in C#. I forgot about that method. :3
Thanks for the answer, and for your other ideas! I would use an if else, but the only reason that I'm using a switch statement is to learn it.
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Switch statement not working C# (answered) 1 Answer
Multiple Cars not working 1 Answer
Sync with visual studio 2010 error 1 Answer