File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

i = i++

 
Peng Fan
Ranch Hand
Posts: 35
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if i equals to 0, then assign i++ to i,but the result is still 0, however in C++, the result is 1, why here in java is 0? THX!
 
Marilyn de Queiroz
Sheriff
Posts: 9059
12
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The results in C++ are variable depending on the OS. The results in Java are always the same independent of the OS.

I think I would never do this in real life. You assign the value of 'i' (in this case '0') to i before the increment happens. On the other hand, if you use i = ++i, you will always increment 'i' before you assign it to 'i'.
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As Marilyn pointed out, "i = i++" is undefined in C++. This is potentially a problem since a program that returned one result when compiled in one OS may return different results when compiled in another OS. In Java, "i = i++" is defined and will always return the same result no matter which compiler or OS you use.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The important point to remember is that in Java, the ++ operator is executed *immediately*, it's just that the result of i++ is the value of i before the increment.

That is,

i = i++;

will *first* increment i, then assign i the value of i before the increment.
 
Irina Goble
Ranch Hand
Posts: 91
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is a link for C++:
C++ Style and Technique FAQ
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic