aboutsummaryrefslogtreecommitdiffstats
path: root/docs/source/arduino/switchcase.rst
blob: 2ca27937c5891059f3922cf35768911871109e10 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
.. _arduino-switchcase:

switch / case statements
========================

Like :ref:`if/else <arduino-else>` blocks, A ``switch`` statement
controls program flow by allowing you to specify different code that
should be executed under various cases.

Syntax
------

::

    switch (var) {
    case val1:
        // statements
        break;
    case val2:
        // statements
        break;
    ...
    default:
        // statements
    }

Where ``var`` is a variable whose value to investigate, and the
``val1``, ``val2`` after each ``case`` are constant values that
``var`` might be.

Description
-----------

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``, the ``switch``
statement will continue executing the following ``case`` expressions
("falling-through") until a ``break`` (or the end of the switch
statement) is reached.

Writing ``default:`` instead of a ``case`` statement allows you to
specify what to do if none of the ``case`` statements matches.  Having
a ``default:`` is optional (you can leave it out), but if you have
one, it must appear after all of the ``case`` statements, as shown
above.

``switch`` statements are often used with an ``enum`` value as the
variable to compare.  In this case, you can write down all of the
values the ``enum`` takes as ``case`` statements, and be sure you've
covered all the possibilities.

Example
-------

::

      switch (var) {
      case 1:
          //do something when var equals 1
          break;
      case 2:
          //do something when var equals 2
          break;
      default:
          // if nothing else matches, do the default
          // default is optional
      }

See also:
---------

`if...else <http://arduino.cc/en/Reference/Else>`_




.. include:: cc-attribution.txt