• Post Reply Bookmark Topic Watch Topic
  • New Topic

problem with infinite loop  RSS feed

 
sovan chatt
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the above code prints small x once..why??while loop is a infinite loop and if condition never gets exected.but still i got the output?!!
 
John Jai
Rancher
Posts: 1776
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Once the maximum value of int is reached, then the value of x starts from the minimum value.

Try below code and check what happens.

 
Pavan Kumar Dittakavi
Ranch Hand
Posts: 108
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is an infinite loop. No doubt about that.

when I ran the application that you have given us, I could see the following output:

small x-2147483648

Also, it is interesting to note that the range of an int in java is [-2,147,483,648 and +2,147,483,647]. So, initially 'x' is set to 0 and it increments each time and finally at a certain time, its sign bit is toggle to 1 making it a negative number and entering the if clause and exiting the loop [as x is now negative].


Thanks,
Pavan.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Pavan Kumar Dittakavi wrote:It is an infinite loop. No doubt about that.

No it's not. You've seen for yourself that the loop ends.
 
Campbell Ritchie
Marshal
Posts: 56570
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tried it and the loop terminated after < 4 seconds.
 
Manoj Kumar Jain
Ranch Hand
Posts: 198
Java Linux Oracle
  • Likes 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is not an infinite loop.

Initially the value of x is 5 and it will increment till 2147483647 (max integer range).
As x is always greater than 3 (x is incresing from 5 to 2147483647 ), so if block will not execute till now.

As soon as we now increment to this value(2147483647 ) by 1 we get the x as -2147483648 now this will qualify the if block and will execute the statement inside the if block

when the condition is checked for the next iteration in the while(-2147483648>1) it fails and program execution stops.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!