Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does the second expression also evaluate to true in this "switch" statement?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading