Next: Specialised Assignment Statements
Up: Further Assignment Statements &
Previous: Further Assignment Statements &
There are some operations that occur so frequently in writing assignment statements that C++ has shorthand methods for writing them.
One common situation is that of incrementing or decrementing an integer variable. For example:
n = n + 1; n = n - 1;
C++ has an increment operator ++
and a decrement
operator --
. Thus
n++;
can be used instead ofn = n + 1;
n--;
can be used instead ofn = n - 1;
The ++
and --
operators here have been written after the
variable they apply to, in which case they are called the
postincrement and postdecrement operators. There are
also identical preincrement and predecrement operators
which are written before the variable to which they apply. Thus
++n;
can be used instead ofn = n + 1;
--n;
can be used instead ofn = n - 1;
Both the pre- and post- versions of these operators appear to be the
same from the above, and in fact it does not matter whether
n++
or ++n
is used if all that is required is to increment the
variable n
. However both versions of the increment and
decrement operators have a side effect which means that they are not
equivalent in all cases. These operators as well as incrementing or
decrementing the variable also return a value. Thus it is possible to
write
i = n++;
What value does i
take? Should it take the old value of
n
before it is incremented or the new value after it is
incremented? The rule is that a postincrement or postdecrement
operator delivers the old value of the variable before incrementing or
decrementing the variable. A preincrement or predecrement operator
carries out the incrementation first and then delivers the new value.
For example if n
has the value 5 then
i = n++;would set
i
to the original value of n
i.e. 5 and
would then increment n
to 6. Whereasi = ++n;would increment
n
to 6 and then set i
to 6.
For the moment this notation will only be used as a shorthand method of incrementing or decrementing a variable.