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.