If statement not working as expected

Jack Burns

New Member
Being as maths is performed strictly from left to right, can anyone see why these 2 subroutines behave differently (on chip and simulator)?

I would expect the Or b1 > $29 in Test1 to cause the subroutine to return with b3 = 0, but that's not happening...

Test1 will return with b3 = 1
Test2 will return with b4 = 0

I know I can code it differently, however I'm just wondering why it's not working as expected.

Rich (BB code):
b1 = $30
b2 = $00

Gosub Test1 ' Doesn't work as expected.
Gosub Test2 ' Works as expected.

End

Test1:
  ' Expected evaluation ((b1 = $29) And (b2 > $00)) Or (b1 > $29)
  b3 = 0
  If b1 = $29 And b2 > $00 Or b1 > $29 Then : Return : End If
  b3 = 1
  Return
 
  
Test2:
  ' Breaking Test 1 down, it works as expected.
  b4 = 0
  If b1 = $29 And b2 > $00 Then : Return : End If
  If b1 > $29 Then : Return : End If
  b4 = 1
  Return
 

Goeytex

Senior Member
It seems to me that it may be compiler limitation where a single "IF" can only test one Boolean expression. The first Boolean expression is evaluated correctly, however the second one is ignored/missed.
 

Aries

New Member
Essentialy, it is because you are mixing ANDs and ORs. From previous experience, all ANDs works, and all ORs works.

If you run your Test1 with b2 = 0 and b2 = 1 for b1 = $00 to $30, it only returns zero for b1 = $29 and b2 = 1.

The evaluation stops after the second term, not because the compiler cannot handle more than one expression, but it cannot handle mixed ANDs and ORs. I imagine it works more-or-less like this:

If ANDs: evaluate first expression. If FALSE, return FALSE otherwise ..
evaluate second expression. If FALSE, return FALSE otherwise ..
evaluate third expression. If FALSE, return FALSE otherwise ..
.... continue until there are no more ANDs

If ORs: evaluate first expression. If TRUE, return TRUE otherwise ..
evaluate second expression. If TRUE, return TRUE otherwise ..
evaluate third expression. If TRUE, return TRUE otherwise ..
.... continue until there are no more ORs
 

Jack Burns

New Member
Many thanks for both of your replies, and for pointing out that ANDs and ORs don’t mix. I will take more care in the future and try not to fall into the same trap again.
 
Top