dcsimg
increment operator jargon
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Anonymous
Posted On:   Tuesday, August 23, 2005 07:44 AM

The following code snippet gives the output
5 and with other compilers ie C++ gives 6 as usual why ?

i=5;
i = i++;
System.out.println(i);

Re: increment operator jargon

Posted By:   Stephen_Ostermiller  
Posted On:   Wednesday, August 24, 2005 06:05 PM

This is one of those stupid idiosyncracies that only people that write compilers need to worry about. ie, make sure your compiler does it the same way that all other Java compilers do it.


This code is ambiguous and nobody should ever use it in the real world. The only people that do, are testing compilers or demonstrating that they know the language better than anybody else. In a real world situation, you would never write code like that, and if you found some written like that you would correct it. Normal programmers would write i=5; i++; or i=5; i=i; or i=5; i=i+1; or i=6; so that the meaning is perfectly clear.


i=i++ could be interpreted two different ways. It is complicated because one statement has two assignments to the same variable. i++ returns the original value of i, then adds one to i and stores it back into i.


Interpretation that returns 6:


i=5;
k=i;
i=k;
i=i+1;


Interpretation that returns 5:


i=5;
k=i;
i=i+1;
i=k;


The only difference between the two interpretations is the order of the two assignments back to i.

About | Sitemap | Contact