Tag: 綺麗なプログラム

  • The switch-case statement in the Arduino language

    The switch-case statement in the Arduino language

    When you want to branch on various conditions in Arduino, you probably write almost everything with if statements.
    But what do you do when there are 10 or 20 branches (rare as that may be)?

    C/C++ has a switch statement, and since the Arduino language is based on C/C++, you can use the same syntax.

    Here is an example program.

    switch (var) {
      case 1:
        // varが1のときに実行する処理
        break;
      case 2:
        // varが1のときに実行する処理
        break;
      default: 
        // どのcaseラベルにも一致しないときに実行する処理
        // defaultは、省略可能
      }

    Here var is a variable: when var is 1, the code under case 1 runs.
    When var is 2, the code under case 2 runs.
    When var is anything other than 1 or 2, the default block runs.

    The “break;” after the code in case 1 and case 2 indicates that the processing for that case has finished.
    Without it, you can run into errors.

    The default block does not need a break; because default is the last branch, so it is obvious that it is the final block.
    That said, writing one is not forbidden—the program works fine either way.

    You can also omit default: itself.
    It feels much like omitting the else in an if-else statement.

    Personally, I find switch-case statements look tidier than if statements when you read the code.
    The syntax isn’t difficult at all, so give it a try.