PDA

View Full Version : IF...ELSEIF problem



Robert Schwartz
02-06-2005, 11:59 AM
I am currently working on a robotics project and I need to use an if elseif statement. The segemnt of code I am using is:

IF (Close_Right = 1) THEN CloseRight
ELSEIF (Close_Left = 1) THEN CloseLeft
ELSEIF (Far_Right = 1) THEN FarRight
ELSEIF (Far_Left = 1) THEN FarLeft
ELSE GiveUp
ENDIF

All of the variables are initialized and all of the labels have contents, but I get the error, "'ELSEIF' must be preceded by 'IF'" whenever I try to tokenize it. What is the matter with my syntax? Thank You.

Robert Schwartz
02-06-2005, 12:17 PM
Problem fixed. Added Goto's before function calls.

Jon Williams
02-06-2005, 09:40 PM
Let me suggest a small style change that will help your program be more readable -- and discover errors like you originally encountered.· When doing anything more than a sing IF-THEN-Label, form your code like this:



IF (Close_Right = 1) THEN
GOTO CloseRight
ELSEIF (Close_Left = 1) THEN
GOTO CloseLeft
ELSEIF (Far_Right = 1) THEN
GOTO FarRight
ELSEIF (Far_Left = 1) THEN
GOTO FarLeft
ELSE
GOTO GiveUp
ENDIF


It doesn't take much more typing, and it does make the structure easier to read.

▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
Jon Williams
Applications Engineer, Parallax
Dallas, TX· USA

Robert Schwartz
02-07-2005, 04:44 AM
Before I fixed the problem, I had it that way, but I got a missing ":" error, so I changed it to the one-line form. Thanks for the advice though.

Jondice
04-07-2005, 10:38 AM
Jon Williams said...
Let me suggest a small style change that will help your program be more readable -- and discover errors like you originally encountered. When doing anything more than a sing IF-THEN-Label, form your code like this:






IF (Close_Right = 1) THEN

GOTO CloseRight
ELSEIF (Close_Left = 1) THEN

GOTO CloseLeft
ELSEIF (Far_Right = 1) THEN

GOTO FarRight
ELSEIF (Far_Left = 1) THEN

GOTO FarLeft
ELSE

GOTO GiveUp
ENDIF





It doesn't take much more typing, and it does make the structure easier to read.


It would appear as though this style is now enforced by the parser http://forums.parallax.com/images/smilies/lol.gif

allanlane5
04-07-2005, 10:51 PM
Yes, actually the
IF (CloseRight=1) THEN CloseRight

is a 'single line version' of the IF statement -- the statement ends with the line-feed.

Thus:
IF (xyz) THEN GoToTarget
ELSEIF (abc) THEN GoToAnotherTarget
' The ELSEIF actually has no 'IF' in front of it,
' since the single-line IF is already done.


The equivalent for your code is:
IF (Close_Right = 1) THEN CloseRight
IF (Close_Left = 1) THEN CloseLeft
IF (Far_Right = 1) THEN FarRight
IF (Far_Left = 1) THEN FarLeft
GOTO GiveUp

Thus you don't need the ELSEIF construct -- it's already built into the code flow.