else

Description

The

if...else
allows greater control over the flow of code than the basic
if
statement, by allowing multiple tests to be grouped. An
else
clause (if at all exists) will be executed if the condition in the
if
statement results in
false
. The
else
can proceed 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 are allowed.

Syntax

1if (condition1) {
2 // do Thing A
3 }
4 else if (condition2) {
5 // do Thing B
6 }
7 else {
8 // do Thing C
9 }

Example Code

Below is an extract from a code for temperature sensor system

1if (temperature >= 70) {
2 // Danger! Shut down the system.
3 }
4 else if (temperature >= 60) { // 60 <= temperature < 70
5 // Warning! User attention required.
6 }
7 else { // temperature < 60
8 // Safe! Continue usual tasks.
9 }

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.