Friday, February 24, 2017

Arduino Conditional Operator

The conditional operator is another decision making construct in Arduino programming.
The conditional operator consists of a condition, which can evaluate to true or false, and two expressions.
If the condition evaluates to true, the conditional expression becomes equal to the first expression. If the condition evaluates to false, the expression becomes equal to the second expression.
The rest of this part of the Arduino programming course will explain and illustrate how the conditional operator works.

Structure of the Conditional Operator

The conditional operator has the following structure:
condition ? first_expression : second_expression;
Where condition will evaluate to either true or false resulting in the entire expression becoming equal to the first expression (if condition evaluates to true) or the second expression (if condition evaluates to false).
As can be seen from the above code, the conditional expression consists of a question mark (?) and a colon (:).
An example sketch follows to show how to use the conditional expression.

Conditional Expression Example Sketch

The sketch below uses the conditional operator to determine which number is the bigger of two numbers.
int val1, val2, result;

void setup() {
  Serial.begin(9600);
  
  // change the values of val1 and val2 to see what the
  // conditional expression does
  val1 = 2;
  val2 = 5;
  // if val1 is bigger than val2, return val1
  // else if val1 is less than val2, return val2
  result = (val1 > val2) ? val1 : val2;
  
  // show result in serial monitor window
  Serial.print("The bigger number is: ");
  Serial.println(result);
}

void loop() {
}
Change the value of the variables val1 and val2 in the sketch, and the bigger of the two numbers will always be displayed in the Serial Monitor window of the Arduino IDE as the video below shows.

How the Sketch Works

The condition (val1 > val2) is evaluated and will either evaluate to true or false.

The Condition Evaluates to False

If val1 is less than val2, the condition evaluates to false. The conditional expression now takes on the value of the second expression – which is val2.
The variable result is then assigned the value of the expression which is val2 (5 in the sketch) and is the bigger number of the two values val1 and val2.

The Condition Evaluates to True

If we change the value of val1 to 12 so that we have:
val1 = 12;
val2 = 5;
val1 is now bigger than val2 and the condition evaluates to true. The conditional expression takes on the value of the first expression – which is val1.
The variable result is assigned the value of the expression which is val1. val1 is the bigger of the two values (with a value of 12).

No comments: