0

Line Robot - Basic lessons - Boolean

A Boolean data is not strictly necessary. There are different data types in C++ and by now we managed to solve all the problems using only 2 of them: int (integer, no decimals) and uint32_t (very big integer). The new type will increase clarity of our program logic.

As the logical expression, a Boolean variable can have one of only 2 values: either "true" or "false". Look at the program:
void RobotLine::loop() {
	static bool yes = false;
	if (yes)
		print("Yes\n\r");
	else
		print("No\n\r");
	yes = !yes;
}
It will be continually displaying "No", "Yes", "No",... Explanation:
  • A logical variable (in our case "yes") is declared as "bool", like in the first line.
  • "yes" is set to value "false".
  • "if" tests the logical expression if parentheses, if it is "true" or "false". As the expression consists only of our variable, and its value is "false", "if" will execute the "else" part, printing "No".
  • The final instruction executes. First the right part is evaluated. That it opposite (negation) of the current value of "yes", which is "false". Therefore, the result will be "true" and that value is stored in "yes".
  • The next pass begins. As "yes" is true, "Yes" will be printed.
  • The last instruction changes "yes" to "false". Etc.

Task: avoid logical variable.

Rewrite the program above so that it doesn't use a Boolean variable.