I would like to know in what way a post fix operator is better than an assignment operator. In other words what are the advantages/limitations of using one over the other.
int a = 10;
a++;
//over
int a = 10;
a += 1;
Thanks.
I would like to know in what way a post fix operator is better than an assignment operator. In other words what are the advantages/limitations of using one over the other.
int a = 10;
a++;
//over
int a = 10;
a += 1;
Thanks.
At first, a++
and a--
are easier to write than a += 1
and a -= 1
.
Also, let's say you want to execute a method and increment a
by one.
Your method head: public static void doSomething(int smth)
Then there are several things you can do: (let's pretend those lines are part of your main method, also int a = 10;
You can use a postfix operator:
doSomething(a++);
//this will at first execute your method with a and then increment it by one
Or you can use the longer version
doSomething(a);
a += 1; //possible too, but longer
Also there is --a
and ++a
which will at first increment a and then hand it over to a method or do something else with it.
There are no real technical limitations of postfix ++
apart from the obvious one: it can only increment by one ... not any other number. Certainly, it makes ZERO difference to performance.
The other possible difference between the two forms is readability. In this case, it is a matter of opinion ... and my opinion is that they are equally readable.
However, if you start embedding postfix and prefix increment / decrement in more complicated expressions, that can significantly damage your code's readability; e.g. try figuring out what a = a++;
does ...