The IF construct allows execution of a statement or series of statements if the calculated expression is true, or of a separate set of statements if it is false.
Format
IF expr THEN statements END [ELSE statements END] |
Parameter(s)
expr |
Any mvBASIC expression to be calculated for its logical value. |
statements |
Statement or set of statements to be executed conditionally. |
The IF construct calculates the given expression for its logical values. The expression is false if it evaluates to 0 or the null string; it is true if it evaluates to anything else. If the expression is true, it then allows the statements following THEN to be executed; if the expression is false, it allows the statements following the ELSE to be executed, or if there is no ELSE portion, it allows program execution to continue with the next executable statement.
Both the THEN clause and the ELSE clause are optional; however, one or the other must be included.
IF constructs may be nested. However, it is recommended to use a CASE construct instead if possible.
Statement Syntax
Although the logistics of the IF construct are relatively simple, the syntax is very exact. These restrictions apply:
Neither THEN nor ELSE can begin a program line. That is, this construct:
IF ANSWER="Y" THEN... |
results in an error message at compile time.
When the statements following the THEN or ELSE are kept on a single line, they must be separated by a semicolon (;). That is, this construct is correct:
IF PROFIT THEN GOSUB 100; PRINT PROFIT ELSE GOSUB 200; PRINT LOSS |
When the statements following the THEN or ELSE are written on more than one line, the THEN or ELSE must be the last word on its line and an END statement must end the set of statements. For example, the above example may be written:
IF PROFIT THEN GOSUB 100 PRINT PROFIT END ELSE GOSUB 200 PRINT LOSS END |
NOTE |
The second variation is much easier to read than the first. |
Example
In this application, IF constructs are nested to calculate the winner in a game of blackjack. It is sometimes difficult to determine which END statement belongs with which THEN or ELSE. A CASE statement is perhaps more appropriate to this function. See CASE Construct for more information.
IF DEALERSCORE > 21 THEN PRINT "I WENT OVER. YOU WIN." YOURWINS = YOURWINS + 1 END ELSE IF NOT(DEALERSCORE < YOURSCORE) THEN PRINT "MY SCORE IS " : DEALERSCORE : ". I WIN." IF DEALERSCORE = YOURSCORE THEN PRINT "" ,"HOUSE RULES-DEALER ALWAYS WINS IN A TIE." MYWINS + = 1 END END ELSE IF NOT(HIT = 11) THEN PRINT "MY SCORE IS " : DEALERSCORE : ". I HAVE TO HOLD. " PRINT "YOU WIN." YOURWINS + = 1 END ELSE PRINT "5 CARDS. I WIN."; MYWINS + = 1 END END |
See Also