Why can't I declare a local variable in a Switch/Case ?????

Here's an interesting problem that I ran across while cleaning up some code in a project I'm working on. Why can't you declare and initialize a local variable inside a Switch/Case statement? For example the code below gives an "jump to case label" error when compiling.

int x = 0;

void setup(){
}

void loop(){
  switch(x){
    case 0:
      int y = 0; //this is the problem
      Serial.print("Number is 0");
      break;
    case 1:
      Serial.print("Number is 1");
      break;
    default:
      Serial.print("No number");
      break;
  }
}

If I change it to declare the variable in one line and assign it a value in the next line like this it works:

int x = 0;

void setup(){
}

void loop(){
  switch(x){
    case 0:
      int y;      //this works fine
      y = 0;     //this works fine
      Serial.print("Number is 0");
      break;
    case 1:
      Serial.print("Number is 1");
      break;
    default:
      Serial.print("No number");
      break;
  }
}

Now this part I really don't understand. If I have a For loop in one of the case's and initialize the variable inside that it works with no errors like this:

int x = 0;

void setup(){
}

void loop(){
  switch(x){
    case 0:
      for(int i = 0;i < 3;i++){
        int y = 0;                   //this works fine
      }
      Serial.print("Number is 0");
      break;
    case 1:
      Serial.print("Number is 1");
      break;
    default:
      Serial.print("No number");
      break;
  }
}

If anyone has an explanation for this behavior I would appreciate it. Thanks.

1 Like

This also works:

  switch(x){
    case 0:
    {
      int y = 0; //this is the problem
      Serial.print("Number is 0");
    }
    break;

The { and } define a local block. At the end of the block the variable goes out of scope, so the compiler is happy.

2 Likes

That makes perfect sense...thanks Paul!

An other thing you can't have in a switch statement is another switch statement inside one of the case blocks. If you want that then you have to call a function with one in.

1 Like

Or put it in a block :slight_smile:

  switch (i)
  {
    case 0:
    {
      switch (j)
      {
        case 0:
          break;
        case 1:
          break;
      }
    }
    break;
    case 1:
    {
    }
    break;
  }

Those last two posting seem to contradict each other? So can one nest switch/case statements or not?

Lefty

Calling a function implicitly creates the code block, so either call a function or insert braces.

Would it be worth including the above knowledge about enclosing blocks of code within brackets, on the reference page at https://www.arduino.cc/en/Reference/SwitchCase ?

protomoose:
Would it be worth including the above knowledge about enclosing blocks of code within brackets, on the reference page at https://www.arduino.cc/en/Reference/SwitchCase ?

This is all standard c/c++, and not at all specific to Arduino...

Regards,
Ray L.