Increment operators for counting - Perl, PHP, C and others
Archive - Originally posted on "The Horse's Mouth" - 2010-10-18 21:05:24 - Graham Ellis
Look at this Perl statement: $counter = $counter + 1;
"Take the value in $counter, add 1 to it, and put it back in $counter". It's a common programing requirement - indeed, so common that you can write it in a shorter form in many languages: $counter += 1;
"Add one to the value led in $counter and store the result there". And when you think about it, there's even a word in English for adding 1 - "increment"; many languages (Perl, PHP, C, C++, Ruby, Java ...) have adopted a special syntax for it too: $counter++
There's an example of this shortening - and other shortenings - on our Perl Programming Course which I've been running in a tailored, single company form today. The original example is [here] and the example showing the shortenings is [here].
Some people (class discussion point - "is this good programming practice?") go a stage further and write statements such as: $oc = $counter++;
or $nc = ++$counter;
Which is going to save the value of counter into a new variable, and also to increment (step it up by one). But beware - there is a difference in what happens here.
• If you write $nc = ++$counter;
then $counter is pre-incremented - in other words, it's increased before a copy is saved into $nc. So - for example - incoming value of $counter is 15, then the outgoing value is also 15 and $nc also gets the value 15
• But if you write $oc = $counter++;
then $counter is post-incremented - in other words, it's only increased after a copy hash been saved into $oc. So - for example - incoming value of $counter is 15, then the outgoing value is also 15 and $oc gets the old value of 14
Personal advise - if in doubt, write it as 2 lines: $cv = $counter; $counter++;
or $counter++; $cv = $counter;
then you'll be sure whether the copy was taken before or after the increment.
Notes:
1. There's also a -- operator (decrement) which uses the same principles in each of the languages I have mentioned
2. One of the most powerful uses of ++ is to increment an array of counters - as you can see [here] in a PHP course example which counts the number of times each picture has been viewed on our web site
3. In C, the ++ operator increments variables that contain integers by 1 as you would expect (example [here]), but if you use it to increment a pointer then the pointer will be stepped up by the size of the variable that's pointed to. So on must C compilers, float *quack;
quack++;
will add 4 to the value held in quack (32 bit float = 4 bytes).
If you're new to C, but have programmed before in another language we offer a C programming course [here]. We also offer a course in C programming for newcomers to programming ([here]) and C++ courses ([here])