zxbasic icon indicating copy to clipboard operation
zxbasic copied to clipboard

Different semantics for condicional expressions

Open EddieTheWild opened this issue 2 years ago • 0 comments

I found out that the so called condictional expressions (e.g. X=(100 and y=5) ), very common in many BASIC dialects (including Sinclair Basic) do not have the expected semantics/evaluation when compiled with ZXB . Instead of returning the value on the right if the condition is True or 0 otherwise, it returns 1 if true, 0 otherwise. See the following example:

Dim x as Integer DIM y as Integer = 0 DIM z as Integer

CLS print " X Y Z" for x=-5 to 10 if x>0 then Y=(666 and (x=5 OR x=8)) +(999 and x=10): z=1 else y=0: z=0 print x;" ";y;" ";z next x end

In Sinclair Basic or Free Basic (https://www.jdoodle.com/execute-freebasic-online) it prints:

X Y Z -5 0 0 -4 0 0 -3 0 0 -2 0 0 -1 0 0 0 0 0 1 0 1 2 0 1 3 0 1 4 0 1 5 666 1 6 0 1 7 0 1 8 666 1 9 0 1 10 999 1

However, same code compiled with ZXB returns:

X Y Z -5 0 0 -4 0 0 -3 0 0 -2 0 0 -1 0 0 0 0 0 1 0 1 2 0 1 3 0 1 4 0 1 5 1 1 6 0 1 7 0 1 8 1 1 9 0 1 10 1 1

There exists an alternative that does go well in ZXB, replacing "(value AND cond)" by "value*(cond)":

if x>0 then Y=666*(x=5 OR x=8) + 999*(x=10): z=1 else y=0: z=0

Moreover, conditional expressions are not valid for string values (I think they are not either in Free Basic, but they are in many dialects including Sinclair Basic):

IF X>0 THEN Y=("hola" AND (X=5 OR x=8))+("adios" AND x=10): Z=0 ELSE Y="kuku": Z=1

Notice that the above alternative for numeric values cannot be applied for strings: "adios"*(x=10) is (and should) not (be) valid.

Conditional expressions are a nice, compact, elegant and clear way to avoid many chained & complex IF sentences (try to translate the above to IF's), mainly when used in THEN or ELSE statements followed by other commands, and I think they could be analized and translated into assembler without facing big problems.

EddieTheWild avatar Nov 08 '23 09:11 EddieTheWild