This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes i = i++ Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "i = i++" Watch "i = i++" New topic
Author

i = i++

Peng Fan
Ranch Hand

Joined: May 04, 2004
Posts: 35
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

Joined: Jul 22, 2000
Posts: 9044
    
  10
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'.


JavaBeginnersFaq
"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
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.


Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
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.


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Irina Goble
Ranch Hand

Joined: May 09, 2004
Posts: 91
Here is a link for C++:
C++ Style and Technique FAQ
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: i = i++
 
Similar Threads
doubt with while loop
how assignement takes place
how to combine between two arraylist if has same value
comparing help!
Division & Modulus Operators