switch...case
Description
Like if statements, switch case controls the flow of programs by allowing programmers to specify different code that should be executed in various conditions. In particular, a switch statement compares the value of a variable to the values specified in case statements. When a case statement is found whose value matches that of the variable, the code in that case statement is run.
The break keyword exits the switch statement, and is typically used at the end of each case. Without a break statement, the switch statement will continue executing the following expressions ("falling-through") until a break, or the end of the switch statement is reached.
Syntax
1switch (var) {2 case label1:3 // statements4 break;5 case label2:6 // statements7 break;8 default:9 // statements10 break;11 }
Parameters
var
: an integer variable whose value to compare with various cases. Any integer data type is allowed*, such as byte
, char
, int
, long
. label1
, label2
: constants. Any integer data type here is also allowed.*You can also use the
data type when you specify just two switch
cases.bool
Note that you can also use negative values as input.
Returns
Nothing
Example Code
1switch (var) {2 case 1:3 // do something when var equals 14 break;5 case 2:6 // do something when var equals 27 break;8 default:9 // if nothing else matches, do the default10 // default is optional11 break;12 }
See also
Suggest changes
The content on docs.arduino.cc is facilitated through a public GitHub repository. If you see anything wrong, you can edit this page here.
License
The Arduino documentation is licensed under the Creative Commons Attribution-Share Alike 4.0 license.