Logical operators (and relational operators) perform tests on multiple relations and return a “true” (non-zero) or “false” (zero) value, which can be used to make decisions:
' jump to label if a = 0
if a == 0 do jump @done; end
' loop until n = 0
loop n = 10 do
while n > 0;
print(n * 4);
n :--;
end
if not p do print("Name not found"); end
SharpBASIC has the following seven logical operators:
not - logical complement and - logical conjunction nor - logical conjunction or - logical inclusive or xor - logical exclusive or eqv - logical equivalence imp - logical implication
Each operator returns a boolean result as indicated below. A “t” indicates the value true and an “f” indicates a value false.
values of value returned by logical operator --------- -------------------------------------- x x x x x x not and nor or xor eqv imp x y x y y y y y y t t f t f t f t t t f f f f t t f f f t t f f t t f t f f t f t f f t t
In an expression, logical operations (also known as boolean operations) are generally performed after arithmetic operations. In complex expressions, parentheses can be used to force operator precedence. If logical operations are performed on non-boolean types, then the types are first converted to boolean, whereby non-zero values are converted to true and zero values are converted to false.
Logical operators are not to be confused with Bitwise Operators.
' SharpBASIC logical and arithmetic operation programming examples
' ----------------------------------------------------------------
option strict;
incl "lib/sys.sbi";
dim x, y: int;
dim r: bool;
main do
x = 1;
y = 0;
' "y + 1" is performed before the "and" operation
if x and y + 1 do
print(true);
else do
print(false);
end
' "x - 1" and "y + 1" are performed before the "or" operation
if x - 1 or y + 1 do
print(true);
else do
print(false);
end
end
Output:
-1
-1
See also: relational operators, bitwise operators