1

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.

nam
  • 55
  • 2
  • 11
  • can the down voter help me correct the question ? I would like to know why one is more preferred than the other. Is my question a duplicate or is it something that shouldn't have been asked ? – nam Aug 05 '16 at 07:45

2 Answers2

1

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.

Adrian K.
  • 118
  • 1
  • 8
0

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 ...

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • a = a++ is something which I would never do. There is no point assigning a = a++ when the increment operator itself does the assignment. Possible answer I would go with increment operator over assignment operator is to reduce my code as pointed by @adrian – nam Aug 05 '16 at 08:45
  • @nam - why is "reducing" your code a goal? The goal *should* be readability ... by yourself AND other people. – Stephen C Aug 05 '16 at 10:57
  • @stephan - Design is actually the reason ! I am trying to follow a coding standard. By the way, I am referring to your answers for this :) [As mentioned here](http://stackoverflow.com/questions/10256068/is-there-a-limit-on-the-number-of-lines-of-code-you-can-put-in-an-eclipse-java-d?noredirect=1&lq=1) – nam Aug 05 '16 at 13:56
  • There is no difference in compiled code size between ++ and += ... if that is what you are talking about. And, frankly, if one of your classes is big enough that this kind of thing made a difference, then it is waaaaay too large. – Stephen C Aug 05 '16 at 14:16