Win a copy of Machine Learning Systems: Designs that scale this week in the Scala forum
or Xamarin in Action: Creating native cross-platform mobile apps in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Operators again  RSS feed

 
Ranch Hand
Posts: 298
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all,

Please check out this program,

int i3 = 0;
i3 = i3++;
i3 = i3++;
System.out.println("The value of i3 is " + i3);

On execution it gives the output as "The value of i3 is 0".
I thought it would be 2,
Please any one explain me whats happening here
 
Ranch Hand
Posts: 195
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nice observation! Just observe what exactly is happening here:

First is, you are assigning the variable 'i3' with the value 0.
Second, you are doing:



What happens here? This is a post-incrementation operation. That means, you are first assigning i3 with the existing value of i3 itself and then immediately incrementing it by 1. But this assigned i3 is now zero itself and not one. If you split up this into two lines of code, it would be like this:



So the third statement also does the very same thing! Finally, the value of i3 is juzt zero. The proper way of doing this would be as follows:



Got the point? Try this out!
 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please look at Corey's tipline on this topic.

Increment Decrement Operators

Hope this helps.
 
village idiot
Bartender
Posts: 1214
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Originally posted by Vijayendra V Rao:

What happens here? This is a post-incrementation operation. That means, you are first assigning i3 with the existing value of i3 itself and then immediately incrementing it by 1. But this assigned i3 is now zero itself and not one. If you split up this into two lines of code, it would be like this:





But when the second line of code is executed, isn't i3 assigned a value of 1? So this example isn't the same as:

i3++ ; is it?

 
author
Sheriff
Posts: 23508
138
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following code:



Can be translated to:



Or in other words, it doesn't really do anything.

Henry
[ January 07, 2005: Message edited by: Henry Wong ]
 
These are the worst of times and these are the best of times. And this is the best tiny ad:
Rocket Oven Kickstarter - from the trailboss
https://coderanch.com/t/695773/Rocket-Oven-Kickstarter-trailboss
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!