This article was automatically translated from Japanese using AI. The Japanese version is the authoritative version.
When you want to branch on various conditions in Arduino, you probably write almost everything with if statements.
But what should you do when you have 10 or 20 branches (unlikely 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 in case 1 runs.
When var is 2, the code in case 2 runs.
When var is anything other than 1 or 2, the default code 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 reason break; is not needed in the default block is that default is the last branch, so it is obvious that it is the final block of code.
That said, there is no rule against writing it—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.
It is not particularly difficult code, so give it a try.
