Spurious warning with logical expression

New to FreeBASIC? Post your questions here.
Post Reply
GWBASICcoder
Posts: 21
Joined: Jul 29, 2022 12:43

Spurious warning with logical expression

Post by GWBASICcoder »

I see a warning with the following code:

Code: Select all

dim l as string = "_"
dim d as boolean = false
dim p as boolean = true
dim r as boolean = true
r = (l = " ") or (l = "_") or ((l = ",") and (d = false) and (p = true))

print "r = "; r
Output:

Code: Select all

logic.bas(5) warning 38(1): Suspicious logic operation, mixed boolean and non-boolean operands
r = true
There is no mix of boolean/non-boolean operands. Compiler issue?

Thanks
fxm
Moderator
Posts: 12107
Joined: Apr 22, 2009 12:46
Location: Paris suburbs, FRANCE

Re: Spurious warning with logical expression

Post by fxm »

- Evaluating numeric or string comparisons like your '(l = "_")' does not provide a Boolean but an Integer with two possible values: '0' (NOK) or '-1' (OK):

Code: Select all

print (0 = 1)
Print (1 = 1)
0
-1
- At opposite, only evaluating boolean comparisons like your '(p = true)' provides a Boolean:

Code: Select all

print (false = true)
print (false = false)
false
true

Therefore, your logical operators mix integer and boolean operands.

To remove the warning, a solution is for example to convert such integer results into boolean:
r = cbool(l = " ") or cbool(l = "_") or (cbool(l = ",") and (d = false) and (p = true))

Note:
There is no specific keyword to convert a boolean into a numeric type, but general syntax like:
Cast(Integer, boolean_variable)
GWBASICcoder
Posts: 21
Joined: Jul 29, 2022 12:43

Re: Spurious warning with logical expression

Post by GWBASICcoder »

Thanks very much! Just noted that a function returning a boolean can coax the integer result of a string compare
to boolean without throwing any warnings.

Code: Select all

function booltest(l as string) as boolean
	return (l = "_")
end function
print "func booltest = "; booltest("_") '---> no warning
Post Reply