aboutsummaryrefslogtreecommitdiffstats
path: root/docs/source/lang/if.rst
diff options
context:
space:
mode:
Diffstat (limited to 'docs/source/lang/if.rst')
-rw-r--r--docs/source/lang/if.rst52
1 files changed, 46 insertions, 6 deletions
diff --git a/docs/source/lang/if.rst b/docs/source/lang/if.rst
index 02ba1e7..bef89e2 100644
--- a/docs/source/lang/if.rst
+++ b/docs/source/lang/if.rst
@@ -2,8 +2,8 @@
.. _lang-if:
-if Statements
-=============
+``if``/``else``
+===============
An ``if`` statement is used to execute code when certain conditions
are met. The general syntax for an ``if`` statement is::
@@ -15,8 +15,8 @@ are met. The general syntax for an ``if`` statement is::
An ``if`` statement first tests whether its *condition* is true (such
as an input being above a certain number). If the condition is true,
the ``if`` statement executes its *body*, which is made up of lines of
-code inside :ref:`curly braces <lang-braces>`. If the condition is
-false, the body is not executed. Here's a more concrete example::
+code inside :ref:`curly braces <lang-curly-braces>`. If the condition
+is false, the body is not executed. Here's a more concrete example::
if (someVariable > 50) {
// do something here
@@ -70,12 +70,52 @@ In the first example, since the body is enclosed in curly braces, both
lines are included. In the second example, since the curly braces are
missing, only the first line is in the ``if`` body.
+``else``
+--------
+
+``if``/\ ``else`` allows greater control over the flow of code than
+the basic :ref:`if <lang-if>` statement, by allowing multiple tests to
+be grouped together. For example, an :ref:`analog input
+<lang-analogread>` could be tested, with one action taken if the input
+was less than 500, and another action taken if the input was 500 or
+greater. The code would look like this::
+
+ if (pinFiveInput < 500) {
+ // action A
+ } else {
+ // action B
+ }
+
+``else`` can precede another ``if`` test, so that multiple, mutually
+exclusive tests can be run at the same time.
+
+Each test will proceed to the next one until a true test is
+encountered. When a true test is found, its associated block of code
+is run, and the program then skips to the line following the entire
+if/else construction. If no test proves to be true, the default
+``else`` block is executed, if one is present, and sets the default
+behavior.
+
+Note that an ``else if`` block may be used with or without a
+terminating ``else`` block, and vice-versa. An unlimited number of
+such ``else if`` branches is allowed. Here is a code example::
+
+ if (pinFiveInput < 500) {
+ // do Thing A
+ } else if (pinFiveInput >= 1000) {
+ // do Thing B
+ } else {
+ // do Thing C
+ }
+
+Another way to express branching, mutually exclusive tests, is with a
+:ref:`switch/case <lang-switchcase>` statement.
+
+
See Also
--------
- :ref:`boolean operators <lang-boolean>`
- :ref:`comparison operators <lang-comparison>`
-- :ref:`else <lang-else>`
-
.. include:: cc-attribution.txt