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:
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:
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;
}
Solution
void RobotLine::loop() {
static int counter = 1;
if (counter++ == 7)
end();
}
Yes, You can do that. The program will first compare "counter" and 7. After that, it will increase "counter" by 1.
If Your solution looks like this, it is also acceptable:
void RobotLine::loop() {
static int counter = 1;
if (counter == 7)
end();
counter++;
}