• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

i = i++

 
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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!
 
Sheriff
Posts: 9109
12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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'.
 
mister krabs
Posts: 13974
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Here is a link for C++:
C++ Style and Technique FAQ
 
reply
    Bookmark Topic Watch Topic
  • New Topic