neilsf / xc-basic3

A BASIC cross compiler for MOS 6502-based machines
MIT License
42 stars 5 forks source link

Question about truth value evaluation #253

Closed orlof closed 5 months ago

orlof commented 7 months ago

Is it allowed to evaluate truth values without comparison operators? e.g.

DIM B AS BYTE
B = 0

IF B THEN
    PRINT "true"
ELSE
    PRINT "false"
END IF

(B=0 should print "false" and b<>0 should print "true")

or should it always have comparison operator e.g.

DIM B AS BYTE
B = 0

IF B<>0 THEN
    PRINT "true"
ELSE
    PRINT "false"
END IF
neilsf commented 7 months ago

Yes, it works. An IF ... THEN statement evaluates an expression and executes the body if it's any non-zero value.

 REM will display true
 IF 42 THEN PRINT "true"
 REM nothing will be displayed
 IF 0 THEN PRINT "false"

A relational expression evaluates to 0 when false or 255 when true. Try the following example:

PRINT 1 < 2 : REM will display "255"
PRINT 1 = 2 : REM will display "0"

I hope this helps.

orlof commented 7 months ago

Thanks for the answer - and this is good news since I have been using that extensively as it seems to generally lead to shorter and faster code.

Anyway, I wanted to verify it because I may have encountered a bug related it.

Following evaluation is not TRUE

IF SHL(1, 3) THEN PRINT "true"

...while this code works perfectly:

IF SHL(1, 3)<>0 THEN PRINT "true"

without optimizer both seem to work ok!

If I put this in loop condition and replace BYTE with LONG it also crashes after (about) 113 iterations:

DIM Count AS WORD
Count = 0

DO
    Count = Count + 1
    PRINT Count
LOOP UNTIL SHL(CLONG(1), 3)

and this crash seems to happen with and without optimizer!

orlof commented 7 months ago

Should I create separate issues from these?

neilsf commented 7 months ago

Should I create separate issues from these?

No thanks, I'll fix it with reference to this issue.