Reference   Language (extended) | Libraries | Comparison

switch / case statements

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.

Parameters

  • var - variable you wish to match with case statements
  • default - if no other conditions are met, default will run
  • break - without break, the switch statement will continue checking through the case statements for any other possible matches. If one is found, it will run that as well, which may not be your intent. Break tells the switch statement to stop looking for matches, and exit the switch statement.

Example

  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
  }

Reference Home

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.