7.10. Increment and decrement operators¶
Incrementing and decrementing are such common operations that C++
provides special operators for them. The ++ operator adds one to the
current value of an int, char or double, and – subtracts
one. Neither operator works on strings, and neither should be
used on bools.
Technically, it is legal to increment a variable and use it in an expression at the same time. For example, you might see something like:
cout << i++ << '\n';
Looking at this, it is not clear whether the increment will take effect before or after the value is displayed. Because expressions like this tend to be confusing, I would discourage you from using them. In fact, to discourage you even more, I’m not going to tell you what the result is. If you really want to know, you can try it.
The active code demonstrates how using increment operators
with cout statements can be confusing.
1#include <cstddef>
2#include <iostream>
3using namespace std;
4
5using std::size_t;
6
7int main() {
8 int x = 0;
9 // We incremented x, so it should print out 1 now right?
10 cout << x++ << '\n'; // Weird, x is still 0?
11}
If you're curious about this, feel free to search up about prefix and postfix increment operators. But for now, just avoid incrementing a variable and using it in an expression at the same time.
Using the increment operators, we can rewrite the letter-counter:
std::size_t index = 0;
while (index < fruit.size()) {
if (fruit[index] == 'a') {
count++;
}
index++;
}
The active code below adds increment operators to our old letter-counter.
1#include <cstddef>
2#include <iostream>
3#include <string>
4
5using std::size_t;
6
7int main() {
8 std::string fruit = "banana";
9 std::size_t count = 0;
10
11 std::size_t index = 0;
12 while (index < fruit.size()) {
13 if (fruit[index] == 'a') {
14 count++;
15 }
16 index++;
17 }
18 std::cout << count;
19}
It is a common error to write something like
index = index++; // WRONG!!
Unfortunately, this is syntactically legal, so the compiler will not
warn you. The effect of this statement is to leave the value of
index unchanged. This is often a difficult bug to track down.
Warning
Remember, you can write index = index +1;, or you can write
index++;, but you shouldn’t mix them.
Q1
Click on the incorrect or not suggested increment statements.
}Re-read the text above and try again.
Re-read the text above and try again.
Re-read the text above and try again.
Correct.
Correct.
Re-read the text above and try again.
Q2
What does the following code print?
1int x = -5;
2while (x < 0) {
3 x++;
4 cout << x << ' ';
5}
Q3
Print every number from 1-10 in this format: "Number 1". Each number should be on its own line.
-
x++; } -
--x; #distractor -
cout << "Number " << x << '\n'; -
cout << "Number " << x; #distractor -
int x = 1; -
while (x <= 10) { -
x = 1; #distractor