Switch Case Problem

When I started this blog I never though I’d post more than every now and then.  But here I posted two days ago and today I’m posting two things.  Whatever!

So this one is easy to find on Stack Overflow but I’m posting it anyway cause it bothered me for a while before I sought it out.  Here’s the stack overflow link.

Inside a switch / case structure I was having these errors with code that when take out and placed in an if / then would compile fine.  It turned out to be variable declarations. Here’s the example:

switch (val)  
{  
case VAL:  
  // This won't work
  int newVal = 42;  
  break;
case ANOTHER_VAL:  
  ...
  break;
}

and the solution:

switch (val)
{   
case VAL:  
{
  // This will work
  int newVal = 42;  
  break;
}
case ANOTHER_VAL:  
...
break;
}

Just put the curly brackets in.  Here’s the explanation from someone named Thomas, ripped right off of Stack Overflow (so sue me):

Case statements are only ‘labels’. This means the compiler will interpret this as a jump directly to the label.The problem here is one of scope. Your curly brackets define the scope as everything inside the ‘switch’ statement. This means that you are left with a scope where a jump will be performed further into the code skipping the initialization. The correct way to handle this is to define a scope specific to that case statement and define your variable within it.

Verified that it worked in my code.

Leave a Reply

Your email address will not be published. Required fields are marked *