Page 1 of 1

for loop with arithmatic expression

Posted: Sun Jun 03, 2012 11:39 pm
by wvoyance
Out of my surprise, the for loop for javascript does not seems to allow arithmetic expression inside the for ( ; ; ) {}.
Is this also true for other languages?

Re: for loop with arithmatic expression

Posted: Mon Jun 04, 2012 12:51 am
by requinix
Perhaps... You have an example?

Re: for loop with arithmatic expression

Posted: Mon Jun 04, 2012 7:37 am
by wvoyance
requinix wrote:Perhaps... You have an example?
I spent several days to hunt for the reason why my loop do not terminate:

function start(str){
isb = parseInt(str.substr(0,12));
for (isb; isb < (isb+3); isb++){
isbn=fix_CheckSum(isb+'');
send_findbooks(isbn);
};
}

When I found the mistake...and went back to look up books and conduct internet search....indeed never an example had an arithmetic expression inside........:(
I thought an advanced programing language like javascript every statement can be compound.

Is this a general rule?

Re: for loop with arithmatic expression

Posted: Mon Jun 04, 2012 9:08 pm
by requinix
The problem is just your logic: you're comparing the loop variable against itself+3. It will always be less than itself+3.

Re: for loop with arithmatic expression

Posted: Tue Jun 05, 2012 7:06 am
by wvoyance
requinix wrote:The problem is just your logic: you're comparing the loop variable against itself+3. It will always be less than itself+3.

oh...really? So, isb+3 will be re-evaluated ever time? (I though it will only be evaluated once at the very beginning.)
so, if I use other arithematic expression will be o.k.?

Re: for loop with arithmatic expression

Posted: Tue Jun 05, 2012 11:05 am
by requinix
wvoyance wrote:oh...really? So, isb+3 will be re-evaluated ever time? (I though it will only be evaluated once at the very beginning.)
The whole thing is evaluated: less-than and addition and all. If you made a copy of isb+3 before the loop and compared isb to that, it would work. Or you can simply loop i=0 to 3 and use isb+i inside.

Re: for loop with arithmatic expression

Posted: Wed Jun 06, 2012 9:48 am
by wvoyance
yes, thanks. I cannot image I made such a simple mistake.