Control Structures

Normal flow of execution is from top to bottom, left to right.  However this flow can be changed using the various control structures available in Basic.

 

Unconditional Branch

An unconditional branch causes execution to jump to another location within the program.  Basic18 has implemented the Goto statement to serve this purpose.

Goto label

label is a single user defined label within the program.  Labels are simply destination points for Goto statements.  They must start in column 1 and end with a colon (:).

Sub test()
  a=10
jmp:
  a=a-1
  If a>0 Then
     Goto jmp
  End If
End Sub

 

It is usually best not to use a Goto statement if you can get by without it.  Too many Goto’s can make a program hard to read and maintain.  However there are times when a Goto can be the best choice. 

A Goto can not jump to a location within another procedure.

 

Decision Structure

Test conditions perform different operations depending on the results.  Basic18 supports the following three decision structures

  1. If Then Else
  2. Select
  3. On x Goto / Gosub


 

If Then Else

Use an If Then structure to execute one or more statements conditionally.

Ues an If Then Else structure to execute one of two blocks of statements.

Syntax:

 If Condition Then
   
True statements
 Else
    False statements
 End If 

Operation:

If Condition is true, then execute True statements
If Condition is false, then execute False statements

Else and False statements are optional

Example:

a=12: b=13
If a>b Then
   ' these statements not executed because a is not greater than b
Else
   ' these statements are executed
End If


 

Select

Select can be thought of as many consecutive IF THEN statements.  The result of the selected expression is compared with the value of each Case statement.  If there is a match, the block of statements associated with that Case is executed.

Select expression
  Case 
value1
      value 1 statements
  Case
value2
    
value 2 statements
 
Case value3
      value 3 statements
  Case Else
     else statements
 End Select

 

In the following example, only test2 will be called and execution will continue after the End Select statement.

 

a=2
Select a
  Case 1: call test1()
  Case 2: call test2()
  Case 3: call test3()
End Select


 

On x Goto / Gosub

This implements a computed goto or gosub statement

 

On expression goto  label list
On
expression Gosub  label list

expression is any expression.
label list
 is a list of comma separated labels

In the following example execution will jump to lbl2 

a=2
On a Goto lbl1,lbl2,lbl3

Because the value of a is 2, execution will jump to the second label in the label list.  If a is zero or negative, or a is greater than the number of labels in the list execution will fall through to the next statement following the On x Goto statement.