Reference   Language (extended) | Libraries | Comparison

switch / case statements

Just like If statements, switch case statements help the control and flow of the programs. Switch/case allows you to make 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 if a match is found.

Parameters

  • var - variable you wish to match with case statements
  • default - if no other conditions are met, default will run
  • break - important, without break, the switch statement will continue checking through the statement for any other possibile 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.