Logical operators precedence

From Liberty BASIC Family
Jump to navigation Jump to search

Description

AND and OR operators do not evaluate according to precedence (AND first).

Example code to demonstrate the bug.

print 1 and 1 or 1 and 0

Expected result in some other languages: 1 (AND should be evaluated first, then we get 1 OR 0, resulting to 1) Instead, we get 0.

Th same thing happens with an IF statement on relational operators:

This would be true in some other programming languages.

x=1: y=1
if x=1 and y =1 or x=1 and y=2 then
    print "It should be TRUE"
else
    print "but it evaluates to FALSE"
end if

Expected: "It should be TRUE"
Instead, "It evaluates to FALSE"

Example code to work around the bug.

Workaround: just use parentheses.

From the help file:

Multiple Conditions

When evaluating multiple conditions, each condition must be placed inside parentheses, as in the examples below.

AND - both conditions must be met for the test to evaluate to TRUE.

a = 2 : b = 5
if (a<4) and (b=5) then [doSomething]

print (1 and 1) or (1 and 0)
x=1: y=1
if (x=1 and y =1) or (x=1 and y=2) then
    print "It should be TRUE"
else
    print "but it evaluates to FALSE"
end if