• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

Why does x=x++ cause infinite loop?

 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why does x=x++ cause infinite loop?
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 );
}
}
 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi,
try this :
int x = 0;
x = x++;
now value of x==0 ( and not 1 ! )
thats why the for loop doesnt stop.
 
Ranch Hand
Posts: 2379
MySQL Database Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Hi Jeremy,
in x=x++ u r trying to assign a value x to the variable x and the increment operator is postfix. If u use prefix the loop i.e x= ++x will execute exactly 5 times plus the last time out of ur loop!

------------------
azaman
 
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
See my detail explanation on i=i++; here,

http://www.javaranch.com/ubb/Forum24/HTML/011163.html
Regards,
Hassan.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic