Hardware Reference
In-Depth Information
Code and Syntax Notes
There are also a couple of new programming concepts introduced in
Example 4-1 .
Local Variables
In the code examples in Chapter 3 , variables were declared outside of the
setup and loop functions. Those were considered global variables because
they can be accessed and changed from either the setup or loop functions.
And when you learn to write your own functions, you could access global
variables within those functions as well.
However, in Example 4-1 , you declared a new variable within the loop function:
int switchState = digitalRead(switchInputPin);
What's important to know about variables declared within a block of code is
that it can only be accessed within that block of code. It's called a local vari-
able . When the Galileo is done executing that particular block, it frees up that
memory for other uses. The block of code where a variable can be accessed
is called its scope .
Therefore, when the loop function has completed a cycle, the switchState
variable is destroyed. A new switchState variable is created the next time the
loop function is executed.
if… else Statements
Building on what you learned in “if Statements” on page 48 , the else state-
ment in Example 4-1 is a way of setting up a block of code to execute when
the if condition evaluates as false.
Here's the basic syntax:
if (condition) {
execute this code if condition is true
}
else {
execute this code if condition is false
}
In Example 4-1 , the if statement checks if the input pin is high. If it is, it will
execute the block of code immediately after it in order to print the text “The
switch is on!” However, if the pin is low, the if condition will evaluate as false
and then Galileo will execute the block of code immediately following the else
statement. This will print “The switch is off!”
You'll never see an else statement without an if statement. But as you saw
in Example 3-2 , you can have an if without an else .
Search WWH ::




Custom Search