[CWC logo] Postfix and Prefix Operators


A Look at Operators

There are larger range of C operators. We already know:


+
-
/ 
*  
%   (remainer or modulus operator)

which have already been introduced. Slightly more advanced are the ++ and -- increment and decrement operators. The ++ operator has already been used as an alternative way of writing:

i = i + 1;

as

++i

The -- operator works in the same way but it subtracts one. That is:

--i

is the same as

i = i - 1;

Now we come to the complicated part. You can use ++ and -- within more complicated expressions and assignments. For example:

a = ++i;

means increment i and then store the results in a. This amazing C instruction is equivalent to:

i = i + 1;
a = i;

That is it does the work of two instructions and its much beloved by the average programmer. The only complication is that you can use the ++ and -- operators in front of or behind a variable and:

a = ++i;

is different from:

a = i++;

The difference comes down to when exactly i is going to be incremented. With ++i the variable is incremented and then the value is used. With i++ the variable is used then the variable is incremented. That is:

a = ++1;

is equivalent to:

i = i + 1; a = i;

but:

a = i++;

is equivalent to:

a = i; i = i + 1;

The same is true for a = --i and a = i-- only one is subtracted from i.

The general principle is that using ++ or -- before a variable means that it is incremented or decremented before it is used in whatever complicated expression it finds itself part of. If you use ++ or -- after a variable then it is used first and the decremented or incremented. C programmers are apt to use it to the point where what is saved is often not worth the increased complexity. For example, what do you think:

result = i++ + --j;

means? If you follow the rules its eventually obvious but it isn't exactly clear! It is in fact equivalent to:

j = j-1; result= i + j; i = i+1;

As a final note remember that operators have a precedence which governs the order in which they are carried out. For example:

a+b*c

actually means

a+(b*c)

rather than

(a+b)*c

because * has a higher precence than +. You can use brackets to ensure that an expression is evaluated in the way you really want. Also notice that spaces do matter.If you write ++i with spaces between the plus signs you will see an error message.


[Leicester University] [] Computer Centre
Information Suppliers: Richard Mobbs, Head of Information Services, Leicester University Computer Centre and Marina Carter, Postgraduate Student, Leicester University Computer Centre.
Last Updated: August 1995