dcsimg
i = i++;
4 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   David_Bates
Posted On:   Monday, January 13, 2003 04:14 AM

OK, I'm trying to understand the behaviour of the following code:



int i = 2;

i = i++;

System.out.println(i) // Prints 2!



Why doesn't the post-increment operator take any effect? Help!!!!

Re: i = i++;

Posted By:   Ivo_Limmen  
Posted On:   Monday, January 13, 2003 06:24 AM

The ++ operator was to help programmers and make coding a little less work. Instread of coding:

i = i + 1;

People could type:

i++;

So doing:

i = i++;

Is a bit redundant... and as you have read in the other comments... it doens't have the desired effect.

Re: i = i++;

Posted By:   Stephen_McConnell  
Posted On:   Monday, January 13, 2003 05:07 AM

Because you just messed with i by re-setting it.


The comiler looks the statemen and evaluates it left to right. Then, executes it right to left. So, it evalutes i to 2, puts it in a register and holds it there. Now it executes the statement. Since it has already used i, it will increment it. Then, it sets i equal to the value it was evaluated to... which was 2.


If you do something like:


int i = 2;
int j = i++;
System.out.println(i); //Prints 3;


If you write tricky ambigous code, you will get ambiguous, unexpected results. This is te stuff they try to trick you on in the Cert.


K.I.S.S.


Stephen McConnell

Re: i = i++;

Posted By:   Anonymous  
Posted On:   Monday, January 13, 2003 05:02 AM

i = i++ does the following :



evaluates the right-hand side ( 2 )
increments i ( 3 )
and sets i equal to the result of the evaluation ( 2 ).


exclude the '=' and use only i++ if you want the result '3' (or use ++i instead)

Re: i = i++;

Posted By:   Andrea_Heller  
Posted On:   Monday, January 13, 2003 05:00 AM

Hi David

In this term you first assign the i to the i and after that, the i will increment. The solution of that problem is:

i = ++i;

Greets

Andrea
About | Sitemap | Contact