Switch Case statement does not work correctly
I run bellow switch-case statement but it does not work. It does not run into some cases.
My code is:
int state = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
switch (state) {
case 0:
Serial.println(state);
break;
case 1:
int aVariable = 0;
Serial.println(state);
Serial.println(aVariable);
break;
case 2:
Serial.println(state);
break;
default:
Serial.println(state);
break;
}
state++;
delay(500);
}
How can I solve it?
Answer
The reason is that you declare a variable inside the case. There are two ways to solve it:
- Declare the variable outside switch-case
int state = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
int aVariable;
switch (state) {
case 0:
Serial.println(state);
break;
case 1:
aVariable = 0;
Serial.println(state);
Serial.println(aVariable);
break;
case 2:
Serial.println(state);
break;
default:
Serial.println(state);
break;
}
state++;
delay(500);
}
- Declare the variable inside a bracket
int state = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
switch (state) {
case 0:
Serial.println(state);
break;
case 1:
{
int aVariable = 0;
Serial.println(state);
Serial.println(aVariable);
break;
}
case 2:
Serial.println(state);
break;
default:
Serial.println(state);
break;
}
state++;
delay(500);
}
You can choose one of the above ways.
Buy Arduino
1 × Arduino UNO Buy on Amazon | |
1 × USB 2.0 cable type A/B Buy on Amazon | |
1 × Jumper Wires Buy on Amazon |
Disclosure: Some links in this section are Amazon affiliate links. If you make a purchase through these links, we may earn a commission at no extra cost to you.
Additionally, some links direct to products from our own brand, DIYables.
Additionally, some links direct to products from our own brand, DIYables.