Differentiate prefix and postfix increment and decrement operators.
5 marks
Answer in brief
The increment operator ++ increases a variable by one. The decrement operator -- decreases it by one. Each has a prefix and a postfix form.
Prefix form
The operator is placed before the variable: ++x or --x. The expression gives the updated value. Starting with x = 5, y = ++x; leaves both x and y equal to 6. Starting with x = 5, y = --x; leaves both equal to 4.
Postfix form
The operator is placed after the variable: x++ or x--. The expression gives the previous value while the variable is updated. Starting with x = 5, y = x++; leaves y equal to 5 and x equal to 6. Starting with x = 5, y = x--; leaves y equal to 5 and x equal to 4.
When used alone
As separate statements, ++x; and x++; both increase x by one. Their difference matters when the expression value is used, as in an assignment. The same rule applies to decrement.
Important points
Writable variable: The operand must be something C permits to be changed. A constant such as 5 cannot be incremented.
Valid range: The updated value must fit the type; signed overflow has no defined result.
Separate changes: Do not use i++ + ++i. It changes i without the required ordering and has undefined behaviour, so there is no guaranteed answer.
Clear code: Use separate statements when several updates would be confusing.