Page 1 of 1

Arithmetric expressions

Posted: Sun Apr 22, 2007 12:10 am
by manu
Hello!
I tend to use arithmetric expressions without the = sign. At first I thought when I write

Code: Select all

a * some_expression
it would be the same as

Code: Select all

a=a*(some_expression)
But "some_expression" is not necessarily evaluated first and then multiplied with "a" and the result stored in "a".
It is more like

Code: Select all

a=a*some_expression
I think the help is not exactly describing this. If some_expression is for example "b+c", it will be like "a" is multiplied with "b" and then "c" is added. The result is stored in "a".
The behaviour is better described as:
An expression without equal sign is evaluated in the normal order and the result is stored in the leftmost variable.
Here is some example code:

Code: Select all

a=7:b=2:c=3
a+b*c
Debug "a="+Str(a)+" b="+Str(b)+" c="+Str(c)

a=7:b=2:c=3
a*b+c
Debug "a="+Str(a)+" b="+Str(b)+" c="+Str(c)

a=7:b=2:c=3
a|b&c
Debug "a="+Str(a)+" b="+Str(b)+" c="+Str(c)

a=7:b=2:c=3
a|(b&c)
Debug "a="+Str(a)+" b="+Str(b)+" c="+Str(c)
It this really the wanted behaviour or is it really a bug? Wouldn't it be nice to have a behaviour like for example in C with +=, -=, *=, /= and so on?
Saves you some braces!

--manu

Re: Arithmetric expressions

Posted: Sun Apr 22, 2007 3:49 am
by PB
Any expression in braces is done BEFORE the rest of the line. Therefore,
a*some_expression will NOT give the same result as a*(some_expression).
If a=1, b=2, c=3, and expr=b+c, then the results will be:

a*expr ; Is calculated as a * b + c, or: 1 * 2 and then 3 added.
a*(expr) ; Is calculated as a * (b + c), or: 1 + (2 * 3).

Pretty simple, and used in all BASIC languages out there.

Posted: Sun Apr 22, 2007 10:12 am
by Trond
Yes, the help is wrong.

Posted: Sun Apr 22, 2007 10:56 am
by PB
Where is it in the Help? I took a look but couldn't see it?

Posted: Sun Apr 22, 2007 11:31 am
by Trond
Variables, types and operators.

Posted: Sun Apr 22, 2007 12:49 pm
by PB
Ah, I missed that when I (quickly) browsed the table of operators. Thanks!
But how is the manual wrong? It quite clearly states: You can use sets of
brackets to force part of an expression to be evaluated first, or in a certain
order.
What's wrong about that?

Posted: Sun Apr 22, 2007 1:37 pm
by Trond
variable*expression ; "variable" will be multiplied directly by the value of "expression"
It says that it uses the value of "expression". However, that is not the case with this line:

Code: Select all

variable = 2
y = 5
z = 7
variable*y+z
Here, the expression is y+z, and its value is 12. Since variable is 2, when it is multiplied by the value of expression, the result should be 24. However, the actual result is 17.

Posted: Sun Apr 22, 2007 1:45 pm
by PB
Now I see what you're saying. Thanks for your patience.