Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Is the postfix++ notation buggy?  RSS feed

 
Jon Camilleri
Ranch Hand
Posts: 664
Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would like to have a practical example when to use postfix notation as opposed to prefix notation, for example:

 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's not a bug - that, precisely, is the difference between ++x and x++ : one is executed before its value is being used in the surrounding expression, and the other is executed afterwards.
 
Stephan van Hulst
Saloon Keeper
Posts: 7806
142
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How can it be a bug? The behaviour is very well specified. That's how it's supposed to work.

Usually, postfix operators are used in nested statements where you need to work with the old value. In Java, I haven't really encountered a lot of uses for it. I came across it more often in C, especially in loops that increase some pointer variable.

However, I think you should write code that doesn't care whether you use prefix or postfix operators. Never use them in nested statements. If you use the unary increment/decrement operators, use them in a separate statement, like this:


You can see that in both examples I used i++ on a separate line. If you code like this, it doesn't matter whether you use i++ or ++i.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!