Reference Language (extended) | Libraries | Comparison
Just like if statements, switch / case statements control the flow of programs. Switch/case allows the programmer to build a list of "cases" inside a switch curly bracket. The program checks each case for a match with the test variable, and runs the code if a match is found.
Switch / case is slightly more flexible than than an if/else structure in that the programmer can determine if the switch structure should continue checking for matches in the case list, after finding a match. If the break statement is not found after running the code for a matched case, the program will continue to check for more matches among the other cases. If a break statement is encountered, case exits the structure, in the same manner as the if/else if construction.
switch (var) { case 1: //do something when var == 1 break; // break is optional case 2: //do something when var == 2 break; default: // if nothing else matches, do the default // default is optional }
Corrections, suggestions, and new documentation should be posted to the Forum.
The text of the Arduino reference is licensed under a Creative Commons Attribution-ShareAlike 3.0 License. Code samples in the reference are released into the public domain.