Hardware Reference
In-Depth Information
Control Structures
The power of microprocessors and microcontrollers is their ability to process
data. They follow instructions, and can also execute conditional instruction
depending on data. Does the variable contain a number greater or equal than
42? If so, execute this portion of code. Otherwise, execute another portion. These
instructions come in the form of conditional statements like
if
,
for
, and
while
.
if Statement
The
if
statement is the simplest of branching statements and is used to detect
if an expression is equal to a result. It is used as follows:
if (expression)
{
statement;
}
Multiple instructions can be used inside an
if
statement, by placing multiple
instructions inside curly brackets:
if (expression)
{
statement;
another_statement;
}
It is also possible to execute two sets of instructions using an
if
..
else
state-
ment. You can think of it as doing one thing
if
the result is equal to something,
else
performs another action.
if (expression)
{
do_this;
}
else
{
do_that;
}
It is also possible to mix several
if
s using
else
:
if (expression)
{
do_this;
}
else if (expression)
{
do_that;
}
Search WWH ::
Custom Search