Hello everyone!
Hi have a question regarding how to use a switch statement for the Arduino IDE.
The thing is that if I declare a variable (i was testing with arrays) inside a case statement the switch function gets stuck on that statement. Reading I found that it requires to wrap the statement on '{}' to define the variable scope.
My question is, why is it necessary to wrap the case on {}? Why isn't the case entry self scoped? Can you help with some links on c++ info regarding to this example?
Example code here, it is for a 1 to 10 counter that resets at 10 and the switch is on handle of comparing the current second (method is for example purpouses):
unsigned long last_millis = 0;
byte state = 0;
void setup() {
Serial.begin(9600);
Serial.println("Switch test");
}
void loop() {
unsigned long current = millis();
if (current - last_millis >= 1000){
last_millis = current;
state ++;
if (state > 10){state = 0;}
Serial.print(call_switch());
Serial.println(" segs");
}
}
byte call_switch (){
byte result = 0;
switch (state){
case 0:{
int char_array = 0;
break;}
case 1:
result = 1;
break;
case 2:
result = 2;
break;
case 10:
result = 10;
break;
default:
result = 42;
break;
}
return result;
}