0

Line Robot - Basic lessons - ++, +=

There are some useful shortcuts in C++ we will be using. They are not necessary but make our code shorter and cleaner to read. Take a look at:
void RobotLine::loop() {
	int counter = 1;
	counter = counter + 1;
}
A variable named "counter" is declared. In the next line "=" sign follows the variable name, meaning assignment. Therefore, the left side ("counter") will become what the right side is. The compiler will first evaluate the right side, resulting in a number that is the next bigger integer, 2. Now, the assignment will follow and counter will become 2. There are 2 ways to make the second line shorter:
  • counter += 1;
  • counter++;
The first form is more versatile because, for example:
counter += 7;
will increase the counter by 7 and the first form doesn't offer a choice of increment.
There are other possibilities, like:
  • counter -= 1;
  • counter--;
The both commands do the same:
counter = counter - 1;

Task: reduce the code.

Reduce the following code:

void RobotLine::loop() {
	static int counter = 1;
	if (counter == 7)
		end();
	counter = counter + 1;
}