I hope some can help me with a beginner question (this is specifically running on Arduino, but I suspect it is a much more fundamental C++ question than that).
I do not understand why the following "switch" statement outputs both "Channel 1" and "Channel 2" statements:
void setup() {
delay(100);
Serial.begin(57600);
delay(100);
int channel = 1;
switch (channel) {
case 1:
Serial.println("Channel 1");
case 2:
Serial.println("Channel 2");
}
}
void loop() {
}
I have read that the switch statements "follow-though" or "cascade", i.e. I understand that if condition 1 is satisfied then the code will still go on to check the subsequent conditions regardless (and you can add an explicit "break" command to jump out). This is all fine.
But I don’t understand that then the second expression evaluates to true (because the integer variable channel=1, and it should only evaluate true when channel=2).
What am I missing here?
Thank you!
>Solution :
You seem to expect it to be like
if (channel == 1)
Serial.println("Channel 1");
if (channel == 2)
Serial.println("Channel 2");
but it’s actually like
if (channel == 1)
goto case1;
if (channel == 2)
goto case2;
goto none;
case1:
Serial.println("Channel 1");
case2:
Serial.println("Channel 2")
none: