If-elseif-else statements - What's wrong?

InvaderZim

Senior Member
If statements don't behave quite like I'd expect in the simulator; is this a feature or a bug? Or a stupid user error? :)

In the following code, 2 inputs are decoded into 1 of 4 states; if there is a problem with decoding, then '99' is returned. The simulator decodes a state, skips the other 'elseif' statements, but then executes the 'else' to return 99.

I would expect the 'else' to be skipped whenever an 'if' (or 'elseif') was executed.

Code:
#picaxe 18x
symbol sel0=input0
symbol sel1=input1

main:
gosub subselect
goto main

subselect:
if sel1=0 and sel0=0 then	'if statement to determine state
b1=1
'goto subselect2
elseif sel1=0 and sel0=1 then
b1=2
'goto subselect2
elseif sel1=1 and sel0=0 then
b1=3
'goto subselect2
elseif sel1=1 and sel0=1 then
b1=4
'goto subselect2
else
b1=99				'should never display
endif
subselect2:			'if/elseif is broken? have to code it with gotos?
return
 

hippy

Ex-Staff (retired)
Looks like a bug to me. All IF / ELSEIF ( except the last ELSEIF ) cause the ELSE to also be executed.
 

westaust55

Moderator
I believe it is down to your assignments:
symbol sel0=input0
symbol sel1=input1
input0 is a reserved word but think it is not used yet (for future X2 parts?)
it is treated as a variable so does not flag a syntax error but it is not equal to input 0 (with a space).

What happens if you try (at work and do not have PE access here)

Code:
#picaxe 18x

main:
gosub subselect
goto main

subselect:
if bit0=0 and bit1=0 then	'if statement to determine state
  b2=1
  'goto subselect2
elseif bit1=0 and bit0=1 then
  b2=2
  'goto subselect2
elseif bit1=1 and bit0=0 then
  b2=3
  'goto subselect2
elseif bit1=1 and bit0=1 then
  b2=4
  'goto subselect2
else
  b2=99				'should never display
endif
subselect2:		'if/elseif is broken? have to code it with gotos?
return
 

InvaderZim

Senior Member
Thanks for the feedback; I changed my symbols to bit0 and bit1 and still get the same behavior in the simulator.

Should I not be using input0, etc.? So far it's worked, though I admit I have some odd behavior with an interrupt that I can't explain.
 

hippy

Ex-Staff (retired)
Using input0 and input1 is okay; they are synonyms for pin0 and pin1 so read the input pins in IF and ELSEIF statements. It is in this case an issue with the simulator having incorrect operation.

As every input condition is tested for, the workround is to remove the ELSE / b2=99 or code it as -

Code:
If sel1 = 0 Then
  If sel0 = 0 Then
    b2 = 1
  Else
    b2 = 2
  End If
Else
  If sel0 = 0 Then
    b2 = 3
  Else
    b2 = 4
  End If
End If
Which uses fewer bytes and is faster to execute on average, but not as short or as fast as ...

b2 = pins & 3 : LookUp b2,(1,2,3,4),b2

Or even simpler ...

b2 = pins & 3 + 1
 

InvaderZim

Senior Member
What a lovely optimization! Thanks Hippy, I can use those in a couple places; chopped 40 bytes off and made everything more readable.
 
Top