PRE/POST INCREMENT/DECREMENT OPERATORS
PRE means do the operation first followed by any assignment
operation. POST means do the operation after any assignment
operation. Consider the following statements
++count; /* PRE Increment, means add one to count */ count++; /* POST Increment, means add one to count */
In the above example, because the value of count is not assigned to any variable, the effects of the PRE/POST operation are not clearly visible.
Lets examine what happens when we use the operator along with an assignment operation. Consider the following program,
#include <stdio.h> main() { int count = 0, loop; loop = ++count; /* same as count = count + 1; loop = count; */ printf("loop = %d, count = %d\n", loop, count); loop = count++; /* same as loop = count; count = count + 1; */ printf("loop = %d, count = %d\n", loop, count); } Sample Program Output loop = 1, count = 1 loop = 1; count = 2
If the operator precedes (is on the left hand side) of the variable, the operation is performed first, so the statement
loop = ++count;
really means increment count first, then assign the new value of count to loop.
Which way do you write it?
Where the increment/decrement operation is used to adjust the
value of a variable, and is not involved in an assignment
operation, which should you use,
++loop_count; or loop_count++;
The answer is, it really does not matter. It does seem that there is a preference amongst C programmers to use the post form.
Something to watch out for
Whilst we are on the subject, do not get into the habit of using
a space(s) between the variable name and the pre/post operator.
loop_count ++;
Try to be explicit in binding the operator tightly by leaving no gap.