Previously, we have added 1 to a variable by writing
A = A + 1;
or
A += 1;
C++ provides an operator which will automatically add 1 to a variable: ++ . We call ++ the incrementing operator since it increments a variable by one. To add one to A we can write:
A++;
or
++A;
Notice that you can have the ++ before or after the variable. If you place the operator after the variable we call it a postfix operator (post as in after). Conversely, the incrementing operator placed before the variable is referred to as a prefix operator (pre as in before).
It is important to note that all provided
examples can be applied to the decrementing operator (--) as well.
As you may have guessed, this operator subtracts 1 from the target variable.
The prefix operator
1) increments/decrements the
variable
2) executes the statement
The postfix operator
1) performs the operation
2) executes the statement
Consider a code example and its output to demonstrate the difference.
#include <iostream.h>
int main() {
int i = 1, Result;
cout << "i: " <<
i << endl;
Result = i++;
cout << "Result: " <<
Result << "; i: " << i << endl;
cout << "i: " <<
i << endl;
Result = ++i;
cout << "Result: " <<
Result << "; i: " << i << endl;
return 0;
}
Output:
i: 1
Result: 1; i: 2
i: 2
Result: 3; i: 3
You should examine this program step by step to verify how the operators work.
To test your understanding, what is the output of the following code?
int i = 1;
cout << (++i)++ <<
endl;
cout << i << endl;
To verify your answer, copy and paste
this in a program and execute it.
I advise that you choose either the
prefix or postfix operator and stick with it.
We will do many examples pertaining to these operators.
Chris Alvin