We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpPrograms › weird for loop i++ overflow
Page Index Toggle Pages: 1
weird for loop i++ overflow (Read 840 times)
weird for loop i++ overflow
Nov 16th, 2007, 7:53am
 
I had a weird error in a bigger program, which I finally chased down to the following piece of code:

void setup() {
 size(120,120);
 noLoop();
 //
 int k1=2147483646;
 int k2=2147483647;
 for (int k=k1; k<=k2; k++) println("k="+k);
 //
}//setup()

void draw() {
}//draw()

(k1 and k2 are valid integers, the loop should print k1 and k2 and stop,
but when k++ is evaluated, k goes from 2147483647 to -2147483648, and the loop goes on)

Re: weird for loop i++ overflow
Reply #1 - Nov 16th, 2007, 9:49am
 
k1 and k2 are valid integers but k2+1 is not, since the integer limit is 2147483647. k2+1 will return -2147483648, which is the lowest limit of an integer.

Code:
int k = 2147483647;
println(k+1);


Since k can't go further than k2 in your loop, k <= k2 is always true. You have to declare k as a 'long' variable to make it work :

Code:
for (long k=k1; k<=k2; k++) println("k="+k); 

Page Index Toggle Pages: 1