Hardware Reference
In-Depth Information
The expression is used to check the veracity of a statement. For example,
you can check to see if a variable is equal to a certain value, less than a value,
greater than a value, and so on. It is also possible to detect other value types;
for example, if a boolean value is true or false .
int myval = 42;
if (myval == 42){
run_this; // myval equals 42; this function will be executed
}else{
run_that; //This one will not
}
if (myval < 50){
run_another_function; //This will be run, since 42 is less than 50
}
Note that in this example, the myval variable is set to the value 42 with a
single equals sign (=), but the value is evaluated with a double equals (==). In
C, a single equal sign always sets the value of a variable (or at least tries to).
Two equal signs makes an evaluation. Watch out when writing if structures;
a single equal sign will force a value into a variable, and the results might not
be quite what you expect!
switch Case
The if statement is easy to use and works well in situations in which you need
to check a variable against one value, possibly two. What would happen if you
need to check against multiple variables? What about a robot that needs to
detect how close an obstacle is? In this case, you might use an if statement; if
the obstacle is less than 3 inches away, then stop the motors. Some situations
are not as simple. Imagine a keypad connected to an Arduino with some stick-
ers on the keypad detailing instructions for the user. If the user presses button
one, then the Arduino will turn on the lights. If the user presses button two,
then the blinds open. If the user presses button three, some music turns on,
and so on. With if statements, this would rapidly get out of hand and would
be difi cult to read:
if (button == 1){
turn_on_lights();
}
if (button == 2){
if (blinds_up == false){
raise_blinds();
blinds_up = true;
}
}
if (button == 3)
 
Search WWH ::




Custom Search