• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Operators again

 
Animesh Shrivastava
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
 
Vijayendra V Rao
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!
 
Kali Praveen
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.
 
Carol Murphy
village idiot
Bartender
Posts: 1203
  • 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?
 
Henry Wong
author
Marshal
Pie
Posts: 21440
84
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic