Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

infinite for loop

 
preeti dengri
Ranch Hand
Posts: 111
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
please look to the following code
public class Q46 {
public static void main(String[]args) {
int x;
int y;
for (x = 0, y = 5 ; x < y ; x=x++)
{
System.out.println( x + " " + y );
}
System.out.println( x + " " + y );
}
}
why this one turned to be an infinite one???producing 0 5 infinite times.
please explain
thank you
 
Jane Griscti
Ranch Hand
Posts: 3141
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi preeti,
The problem is <code>x=x++</code> ... x is always 0! The postfix operator <code>x++</code> is evaluated first, followed by the assignment.
This code is evaluated as:
<pre>
take the value of x(0)
increase it by 1 and store in memory
assign the original value of x(0) to x, overwriting the stored value of x(1)
</pre>
Use <code>x++</code> instead.
Hope that helps.
------------------
Jane Griscti
Sun Certified Programmer for the Java� 2 Platform
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic