There are other assignments that occur so commonly, C++ provides special operators for them, too. For example, if x and y are integer variables, then in place of having to write
| x = x + 1; | and | y = y - 1; |
| x++; | and | y--; |
| ++x; | or | x++; |
int x1,
x2,
prefixResult,
postfixResult;
cin >> x1; // input a value
x2 = x1; // make a copy
prefixResult = ++x1, // save result of prefix form
postfixResult = x2++; // save result of postfix form
// display results
cout << " x1: " << x1 << " x2: " << x2 << endl
<< " prefix produced: " << prefixResult
<< " postfix produced: " << postfixResult
<< endl;
Take a few moments to study this experiment, until you understand what it
is doing.
Then add it to express.cpp and use it to experiment with a
variety of input values.
Report your findings in the space below:
The decrement operator (--) works in exactly the same fashion, except that it subtracts 1 from its operand, instead of adding one.
You should now be aware of the C++ shortcuts for the increment and decrement operations, and also understand how the prefix version of each operator differs from the postfix version.
Forward to the Next Experiment