for loop with arithmatic expression

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
wvoyance
Forum Contributor
Posts: 135
Joined: Tue Apr 17, 2012 8:24 pm

for loop with arithmatic expression

Post 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?
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: for loop with arithmatic expression

Post by requinix »

Perhaps... You have an example?
User avatar
wvoyance
Forum Contributor
Posts: 135
Joined: Tue Apr 17, 2012 8:24 pm

Re: for loop with arithmatic expression

Post 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?
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: for loop with arithmatic expression

Post 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.
User avatar
wvoyance
Forum Contributor
Posts: 135
Joined: Tue Apr 17, 2012 8:24 pm

Re: for loop with arithmatic expression

Post 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.?
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: for loop with arithmatic expression

Post 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.
User avatar
wvoyance
Forum Contributor
Posts: 135
Joined: Tue Apr 17, 2012 8:24 pm

Re: for loop with arithmatic expression

Post by wvoyance »

yes, thanks. I cannot image I made such a simple mistake.
Post Reply