Post increment and decrement

Jonathan M Davis via Digitalmars-d digitalmars-d at puremagic.com
Fri Mar 13 22:29:58 PDT 2015


On Wednesday, March 11, 2015 17:23:13 welkam via Digitalmars-d wrote:
> Observation Nr. 1
> People prefer to write var++ instead of ++var.
>
> Observation Nr. 2
> Because of observation Nr. 1 and other reasons compilers became
> good at removing code that is not needed making var++ and ++var
> to produce the same code if returned value is not used.
>
> Observation Nr. 3
> Because of observation Nr. 2 more people use var++ in place where
> they really only need ++var.
>
> Observation Nr. 4
> Because of observation Nr. 3 people learning to program may
> mistakenly learn that var++ is just incrementing. (I am included
> in that list)
>
> Observation Nr. 5
> Because of observation Nr. 4 people can write slower than
> necessary code for classes with overloaded operator or even get
> bugs.
>
> Because of all this why not make only one increment/decrement
> operator and have post increment/decrement to be called by
> template name, because it is a template?
>
> template post_inc(T) {
> auto tmp = T;
> T++;
> return tmp;
> }

Well, much as I hate it when folks use postincrement when preincrement will
do, D solved the problem by making it so that they're overloaded with the
same operator, so unlike in C++, in D, the compiler is _always_ able to
replace a postincrement expression with a preincrement expression if it
doesn't matter which is used.

So, while I'm in the habit of correcting folks who use i++ when they should
use ++i in C++, there really isn't any point in D except insomuch as it will
make you a better programmer in other languages if you get into the habit of
using preincrement when either will work.

- Jonathan M Davis



More information about the Digitalmars-d mailing list