As someone who is fairly new to programming, you are sure to have seen the increment and decrement operators. It is also likely that you seen two forms of these operators which may lead to confusion. These operators are almost universal to every language. Below is an example of Pre-increment and Post-increment.
You may be under the impression that these two statements are equal and that it doesn’t matter which you use, however this isn’t always true. In most situations it doesn’t matter which form of the operator you use, but there are some cases that it does make a difference, and learning the difference can lead to some clever coding.
First of all what do this operators do? Each of these operators increment the value by one as we already know, but these operators also have a return value. Pre increment will increment the current value by one and then return the incremented value. So if we have the following code…
int i = 3;
int x = ++i;
x will be equal to 4 and i will be also be equal to 4.
However with post increment, it will return the current value of i and then increment i. So with the same example using post-increment…
int i = 3;
int x = i++;
x will be equal to 3 and i will be equal to 4.
These examples are about as basic as it gets, but it is very useful to know the difference between these two statements as it can often save you a line of extra code here and there. Placing the statement within a function call, or when accessing an element of an array are just two examples of ways that you can make your code look nicer.
I hope this helped clear up the topic for you, please leave comments or feel free to send me an email if you have any questions!