Jump to content

Why? Loop Conditions


You are about to reply to a thread that has been inactive for 1797 days.

Please take a moment to consider if this thread is worth bumping.

Recommended Posts

Hi All,

Had a snippet of code that was driving me mad .. got it fixed but I do not understand what was going on ... here is what I had (redacted for clarity)

integer num = 8;
integer found = FALSE;
while (num -= 2 >= 0 && !found)
{
	//do something to check found
}

What was hapening was that with the code was running through the loop SEVEN times, as opposed to the four that I would expect, going from 7 to 1.

I got it to work by enclosing the 'num -= 2' in parenthesis. FIne, undertand about forcing the calculation prior to the conditional check or whatever ... what I do not get though is the behaviour seen without the parenthesis. Why would it do a -1 of num?

Link to comment
Share on other sites

See operator precedence: http://wiki.secondlife.com/wiki/LSL_Operators

The -= and >= operators share precedence, so they will be evaluated "at the same time" from right to left.

// original line:
while (num -= 2 >= 0 && !found) {...}

// what happens:
while ((num -= (2 >= 0)) && !found) {...}

// (2 >= 0) becomes TRUE aka 1
while ((num -= (1)) && !found) {...}

 

Edited by Wulfie Reanimator
  • Like 1
  • Thanks 1
Link to comment
Share on other sites

Dam, pipped at the post!

A similar gotcha can occur when one of your comparisons contains a function call, it is crucial to satisfy yourself that you know the sequence in which all the values to be tested will occur.

I would always recommend parenthesising any complex test anyway, but that's just me, I'm old, I can't keep as much in my short-term memory as I used to, and I've made exactly this sort of mistake so many times in the past...

  • Haha 1
Link to comment
Share on other sites

7 hours ago, Wulfie Reanimator said:

LSL's operator precedence is pretty in-line with other languages, in fact it's almost identical with C# (my other language).

Yeah but from memory there is a weird quirks related to && || operations that has me put parenthesis just to be sure.

Edited by Kyrah Abattoir
Link to comment
Share on other sites

You are about to reply to a thread that has been inactive for 1797 days.

Please take a moment to consider if this thread is worth bumping.

Please sign in to comment

You will be able to leave a comment after signing in



Sign In Now
 Share

×
×
  • Create New...