1. Lesson 7: Autoincrement and Autodecrement Operators in C++
Discussion
1. C++ uses autoincrement and autodecrement operators, such that if we have a variable count,
count++; would add 1 to count in the same way that the assignment statement count = count + 1;
does, and count-- would subtract 1 from count, in the same way that count = count -1; does.
2. Recall that count = count + 1 may also be expressed as count += 1.
3. Recall that count = count - 1 may also be expressed as count -= 1.
4. In C++, we are allowed to express count +=1 as count++.
5. In C++, we are allowed to express count -=1 as count--.
6. Looks simple enough. However, there is another expression that looks very similar, and that can
add or subtract 1 to a variable: ++count and --count.
7.Needless to say, we can only do this to integer variables, and not only to the variable count, but to
other variables as well, so we can have vote++, --candy, and the like.
8. Moreover, we can only apply the increment and decrement operators to single variables.
Expressions like (count+i)++ , or -–(x+y) are not allowed in C++.
9. When the operator is placed before the variable, say, ++count, the operator ++ is in prefix form;
putting it as count++ renders it in postfix form.
10. What's the difference? Let's consider putting the expression in an assignment statement. Recall
that the expression, say count++, is actually an assignment statement in itself, so that you we shall
be doing more than one assignment in the statements below:
m= 1;
j = 2 * m++;
11. In this postfix form, the following things happen:
1. The old/current value of m, which is 1, is multiplied by 2
2. The old/current value of m is incremented by 1 (which means that new value of 2 is
assigned to m)
3. The result of multiplication is stored or assigned to j.
Take note that there were two assignment operations done: one on m andthe other on j.
12. If we have the following statements instead:
m= 1;
j = 2 * ++m;
the following steps would be executed:
1. The old/current value of m which is 1 is incremented, making it 2 (The first assignment)
2. This new value of m is multiplied by 2
3. The product of the multiplication is stored or assigned to j.(Second assignment)
Sample Programs:
1. incDecPost.cpp
2. incDecPre.cpp
Exercise:
1. Try the sample program incDec.cpp given in incDecSourceFile.pdf and study the operations
done by the prefix and postfix increment and decrement operators.
2. What happens if you remove line#26? Explain the output when this line is removed.
Submit your explanation in pdf format with filename incDecfLastname.
3. Create a program that will output two columns, with headings “Text”, and “Numeral”, for
numbers 1 through 5. File name is tabLastname.cpp. Sample output is shown below.
Text Numeral
One 1
Two 2
: :
TSPaccarangan Increment and Decrement Operators September 14, 2009