Section 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 string
s, and neither should be used on bool
s.
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++ << endl;
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.
cout
statements can be confusing.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:
int index = 0;
while (index < length) {
if (fruit[index] == 'a') {
count++;
}
index++;
}
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.
Checkpoint 7.10.1.
Checkpoint 7.10.2.
What does the following code print?
int x = -5;
while (x < 0) {
x++;
cout << x << " ";
}
- 5 4 3 2 1
- Notice that x is negative.
- -5 -4 -3 -2 -1
- Notice that the value of x is incremented before it is printed.
- -4 -3 -2 -1 0
- The value of x is incremented before it is printed so the first value printed is -4.
Checkpoint 7.10.3.
Print every number from 1-10 in this format: “Number 1”. Each number should be on its own line.
You have attempted 1 of 6 activities on this page.