Sunday, August 25, 2013

Increment/Decrement Operators

Incrementing (adding 1 to) and decrementing (subtracting 1 from) a variable are so common that they have their own operators in C. There are actually two version of each operator — a prefix version and a postfix version.
OperatorSymbolFormOperation
Prefix increment++++xIncrement x, then evaluate x
Prefix decrement––––xDecrement x, then evaluate x
Postfix increment++x++Evaluate x, then increment x
Postfix decrement––x––Evaluate x, then decrement x

The prefix increment/decrement operators are very straightforward. The value of x is incremented or decremented, and then x is evaluated. For example:
1
2
int x = 5;
int y = ++x; // x is now equal to 6, and 6 is assigned to y
The postfix increment/decrement operators are a little more tricky. The compiler makes a temporary copy of x, increments x, and then evaluates the temporary copy of x.
1
2
int x = 5;
int y = x++; // x is now equal to 6, and 5 is assigned to y
In the second line of the above example, x is incremented from 5 to 6, but y is assigned the value of the copy of x, which still has the original value of 5.
Here is another example showing the difference between the prefix and postfix versions:
1
2
3
4
5
6
int x = 5, y = 5;
cout << x << " " << y << endl;
cout << ++x << " " << --y << endl; // prefix
cout << x << " " << y << endl;
cout << x++ << " " << y-- << endl; // postfix
cout << x << " " << y << endl;
This produces the output:
5 5
6 4
6 4
6 4
7 3
On the third line, x and y are incremented/decremented before they are evaluated, so their new values are printed by cout. On the fifth line, a temporary copy of the original values (x=6, y=4) is sent to cout, and then the original x and y are incremented. That is why the changes from the postfix operators don’t show up until the next line.

1 comment:

  1. This Website is Easy to Learn and usefull and my douts is remove after learn this website.

    ReplyDelete