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:

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); }
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
Please note: These are affiliate links. If you buy the components through these links, We may get a commission at no extra cost to you. We appreciate it.

The Best Arduino Starter Kit

※ OUR MESSAGES