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.

++i; //Pre-Increment

i++; //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!

Sign up for our newsletter so you dont miss new deals and anouncements!

Please follow and like us:
Categories: Programming

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

D

Dplug For Developing VST Plugins on Linux

Developing VST Plugins for Linux is something that has always been of great interest to me personally.  There never seemed to be a framework that was easily portable to Linux aside from JUCE.  Why not Read more…

Audio

Linkwitz-Riley Crossovers – Digital Multiband Processing

When it comes to Digital Signal Processing, successfully creating crossovers can be tricky at first.  Linkwitz-Riley filters have a very important quality that when a highpass and lowpass filter with the same corner frequency are summed, Read more…

D

D – An Elegant Language For A More Civilized Age

This is from a paper that I wrote for one of my classes recently and would like to share it here. Nearly every native application running on modern computers was written using C++.  The language Read more…