Why? Loop Conditions

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?

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
• 1
• 1

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...

Share on other sites

AHHH <face palm> ... of course should have thought of that .... coding 101 .. thanks so much @Wulfie Reanimator

Share on other sites

Precedence is funny in LSL sometimes, parenthesis don't cost anything memory/speed wise, so use them anytime you have doubts.

Share on other sites
2 hours ago, Kyrah Abattoir said:

Precedence is funny in LSL sometimes, parenthesis don't cost anything memory/speed wise, so use them anytime you have doubts.

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

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

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

Only 75 emoji are allowed.

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×

×
×
• Create New...