|
|
|
|
|
|
|
which is much better. In algebra this expression would be meaningless, but in C++ it is read as add two to the value in myAge and assign the result to myAge. |
|
|
|
|
|
|
|
|
Even simpler to write, but perhaps a bit harder to read is |
|
|
|
|
|
|
|
|
The self-assigned addition operator (+=) adds the r-value to the l-value and then reassigns the result into the l-value. This operator is pronounced plus-equals. The statement would be read myAge plus-equals two. If myAge had the value 4 to start, it would have 6 after this statement. |
|
|
|
|
|
|
|
|
There are self-assigned subtraction (-=), division (/=), multiplication (*=), and modulus (%=) operators as well. |
|
|
|
|
|
|
|
|
New Term: The most common value to add (or subtract) and then reassign into a variable is 1. In C++ increasing a value by 1 is called incrementing, and decreasing by 1 is called decrementing. There are special operators to perform these actions. |
|
|
|
|
|
|
|
|
The increment operator (++) increases the value of the variable by 1, and the decrement operator () decreases it by 1. Thus, if you have a variable, c, and you want to increment it, you would use this statement: |
|
|
|
|
|
|
|
|
C++; // Start with C and increment it. |
|
|
|
|
|
|
|
|
This statement is equivalent to the more verbose statement |
|
|
|
|
|
|
|
|
which you learned is also equivalent to the moderately verbose statement |
|
|
|
|
|
|
|
|
New Term: Both the increment operator (++) and the decrement operator () come in two flavors: prefix and postfix. The prefix variety is written before the variable name (++myAge); the postfix variety, after (myAge++). |
|
|
|
|
|
|
|
|
In a simple statement, it doesn't much matter which you use, but in a complex statement, when you are incrementing (or decrementing) a variable and then assigning the result to another variable, it matters very much. The prefix operator is evaluated before the assignment; the postfix is evaluated after. |
|
|
|
|
|